Tkinter Label not showing Int variable

守給你的承諾、 提交于 2021-02-08 12:02:36

问题


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()

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


回答1:


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.

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()

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(...).

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



来源:https://stackoverflow.com/questions/24139166/tkinter-label-not-showing-int-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!