不按按钮即可自动刷新tkinter标签

时间:2018-09-14 16:52:00

标签: python tkinter

您好,我正在tkinter中建立一个简短的游戏,希望能够通过tkinter窗口中的标签向用户输出。我看了过去的问题,除了使用按钮(不是我希望它执行的操作)使它刷新之外,没有任何帮助。简而言之,我需要在每次更改变量时刷新它。

我的代码:

import tkinter as tk
import time

root = tk.Tk()
root.resizable(width=False, height=False)
w = 800 # width for the Tk root
h = 500 # height for the Tk root
ws = root.winfo_screenwidth() # width of the screen
hs = root.winfo_screenheight() # height of the screen
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
root.geometry('%dx%d+%d+%d' % (w, h, x, y))
wheat=10
money=0
title=tk.Label(root, text="The Farm Game")
title.config(font=('times', 20, 'bold'))
title.place(height=30, width=300, x = 250 , y = 10)


def advance():
    moneyguidisplay = tk.StringVar()
    moneyshowed = ("£", money)
    moneyguidisplay.set(moneyshowed)
    moneygui = tk.Label(root, wraplength=200, textvariable=moneyguidisplay)
    moneygui.config(bg='lightgreen', font=('times', 15, 'bold'))
    moneygui.place(height=30, width=200, x=600, y=60)
    Usershow = tk.StringVar()
    shownow = ("Welcome to The farm game")
    Usershow.set(shownow)
    USER = tk.Label(root, wraplength=200, textvariable=Usershow)
    USER.config(bg='lightpink', font=('times', 15, 'bold'))
    USER.place(height=200, width=400, x=200, y=100)
    wheatguidisplay = tk.StringVar()
    wheatshowed = ("Wheat:", wheat)
    wheatguidisplay.set(wheatshowed)
    Wheatgui = tk.Label(root, wraplength=200, textvariable=wheatguidisplay)
    Wheatgui.config(bg='lightblue', font=('times', 15, 'bold'))
    Wheatgui.place(height=30, width=200, x=0, y=60)
    root.after(100, advance)

root.after(100, advance)

root.mainloop()

1 个答案:

答案 0 :(得分:1)

您的问题还不清楚,但是我能理解的是,您希望能够根据另一个变量的值来更改Label的文本(如果我错了,请纠正我)。您可以使用config方法来这样做。我为此编写了一个小函数,您可以将其放入程序中。

from tkinter import*

root=Tk()

L=Label(text="Label text changing after 5 sec")
L.grid()

# Call this function where the value of your variable/number changes
def ChangeValue(num):
    L.config(text=str(num))
    print("Value Changed")
root.update()
root.after(5000,lambda :ChangeValue("Text Changed!"))
root.mainloop()