Python 不按按钮时自动刷新tkinter标签
你好,我正在tkinter中构建一个短游戏,希望能够通过tkinter窗口中的标签输出给用户。我查看了过去的问题,发现除了使用按钮让它刷新之外没有任何帮助,我不希望它这样做。简而言之,每次变量更改时,我都需要刷新它 我的代码:Python 不按按钮时自动刷新tkinter标签,python,tkinter,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 # hei
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()
您的问题有点不清楚,但我能理解的是,您希望能够根据另一个变量的值更改标签的文本(如果我错了,请更正我)。您可以使用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()
你在问什么标签?你需要什么帮助?看来您知道
after
和configure
方法,这是完成工作所需的全部。非常感谢您,我一直在玩弄after方法,无法理解它。谢谢,如果有帮助,请接受我的回答。很乐意帮忙!:)您好,我再次将其植入我的代码中,并且正在努力找出如何调用标签文本中的更改,而不是基于时间,而是当我在程序中调用它时,您可以解释一下吗?因此,您不希望延迟,但是,您希望更改标签文本(如果我错了,请纠正我)?只需从代码中的任何地方调用此函数,就像其他普通函数一样。只需注意要更改的标签是在范围(调用函数的地方)中定义的。