Tkinter标签不显示Int变量 [英] Tkinter Label not showing Int variable

查看:77
本文介绍了Tkinter标签不显示Int变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个简单的RPG,当您收集黄金时,它将在标签中显示,但是没有! 这是代码:

I'm trying to make a simple RPG where as you collect gold it will be showed in a label, but it doesn't!! Here is the code:

def start():

    Inv=Tk()

    gold = IntVar(value=78)


    EtkI2=Label(Inv, textvariable=gold).pack()

我是python的新手,尤其是tkinter,所以我需要帮助!

I'm new to python and especially tkinter so I need help!!!

推荐答案

代码唯一的错误是您没有调用根窗口的mainloop方法.完成后,您的代码可以正常工作.

The only thing wrong with your code is that you aren't calling the mainloop method of the root window. Once you do that, your code works fine.

这是一个经过稍微修改的版本,可在5秒后更新该值:

Here's a slightly modified version that updates the value after 5 seconds:

from Tkinter import *

def start():
    Inv = Tk()
    Inv.geometry("200x200")

    gold = IntVar(value=78)
    EtkI2=Label(Inv, textvariable=gold).pack()

    # chanage the gold value after 5 seconds
    Inv.after(5000, gold.set, 100)

    # start the event loop
    Inv.mainloop()


start()

您的代码还有其他一些可以改进的地方.例如,EtkI2将设置为None,因为这是pack()返回的结果.最好将小部件的创建与小部件的布局分开.另外,最好进行全局导入(from Tkinter import *).我推荐import Tkinter as tk ... tk.Label(...).

There are some other things that could be improved with your code. For exaple, EtkI2 will be set to None since that is what pack() returns. It's best to separate widget creation from widget layout. Also, it's better to not do a global import (from Tkinter import *). I recommend import Tkinter as tk ... tk.Label(...).

我将在此处解释更多有关使用面向对象方法的信息: https://stackoverflow.com/a/17470842

I explain more about that along with using an object-oriented approach here: https://stackoverflow.com/a/17470842

这篇关于Tkinter标签不显示Int变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆