我试着每2.5秒更新一个变量,但不知怎么它不会显示在Tkinter上。在
我写了所有的代码,除了与Tkinter相关的东西,因为我在这方面的知识很少。我操纵了一个网站上的代码,给出了一个使用Tkinter的例子。在
代码如下:
import threading
from tkinter import *
def onclick():
pass
its1_c = 0 # first upgrade amount
its2_c = 0 # second upgrade amount
ITS1 = its1_c * 30 # amount of first upgrade owned x multiplier to money
ITS2 = its2_c * 70 # amount of second upgrade owned x multiplier to money
cashflow = 0
balance = 100
def moneygain():
global cashflow
global balance
global text
text = balance
cashflow = balance
threading.Timer(2.5, moneygain).start()
cashflow = cashflow + 10
cashflow = cashflow + ITS2
cashflow = cashflow + ITS1
balance = cashflow
print("Balance: " + str(balance))
text.insert(INSERT, balance)
root = Tk()
text = Text(root)
text.insert(INSERT, balance)
text.pack()
text.tag_add("here", "1.0", "1.4")
text.tag_add("start", "1.8", "1.13")
text.tag_config("here", background="yellow", foreground="blue")
text.tag_config("start", background="black", foreground="green")
root.mainloop()
moneygain()
当我试图显示“平衡”时,它不会更新。相反,它会抛出以下错误:
^{pr2}$如何在Tkinter窗口上显示balance
?在
要解决在tkinter上更新
balance
变量的问题,我的解决方案如下:Tkinter确实不喜欢老式的线程,并且使用函数
.after()
可以更好地工作,就像在moneygain()
的最后一行一样我还采取了创造性的自由,把你的
Text
小部件换成了Label
。正如您所说的,您不熟悉该语言,我非常肯定在这种情况下,Label
比Text
更合适(至少对于这个问题的修复!)。在另一个建议:当您要多次调用一个函数时(就像我们多次调用
moneygain
),最好不要在这些函数中创建小部件。当我测试您的代码时,它无限地生成新的Text
小部件,因为它被反复调用(同样,可能不是您想要的)。在Tkinter一开始很难学,但一旦你学会了,它真的很有趣!祝你的项目好运!在
相关问题 更多 >
编程相关推荐