简体   繁体   English

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

[英]Refresh tkinter label automatically not on button press

Hi there i am building a short game in tkinter and would like to be able to output to the user via a label within my tkinter window. 嗨,我正在tkinter中建立一个简短的游戏,希望能够通过tkinter窗口中的标签向用户输出。 I have looked at past questions and found no help apart from getting it to refresh using a button which is not what i want it to do. 我看了过去的问题,除了使用按钮(不是我希望它执行的操作)使它刷新之外,没有任何帮助。 In short i need to have it refresh everytime a variable is changed. 简而言之,我需要在每次更改变量时刷新它。

My code : 我的代码:

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

Your question is a little unclear, but what I can understand is that you want to be able to change the text of a Label, depending on the value of another variable(correct me if I'm wrong). 您的问题还不清楚,但是我能理解的是,您希望能够根据另一个变量的值来更改Label的文本(如果我错了,请纠正我)。 You can use the config method to do so. 您可以使用config方法来这样做。 I have written a small function for it, you can put it in your program. 我为此编写了一个小函数,您可以将其放入程序中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM