如何在python中设置Tkinter来显示和更新变量?

2024-10-02 08:26:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着每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?在


Tags: 代码textimporttkinterdeftagrootamount
1条回答
网友
1楼 · 发布于 2024-10-02 08:26:08

要解决在tkinter上更新balance变量的问题,我的解决方案如下:

  from Tkinter import *

  root = Tk()
  moneyShown = Label(root, font=('times', 20, 'bold')) #use a Label widget, not Text
  moneyShown.pack(fill=BOTH, expand=1)
  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

      cashflow = cashflow + 10
      cashflow = cashflow + ITS2
      cashflow = cashflow + ITS1
      balance = cashflow
      print("Balance: " + str(balance))

      moneyShown.configure(text="Balance: "+str(balance)) #changes the label's text
      moneyShown.after(2500, moneygain) #tkinter's threading (look more into how this works)
  moneygain()
  root.mainloop()

Tkinter确实不喜欢老式的线程,并且使用函数.after()可以更好地工作,就像在moneygain()的最后一行一样

我还采取了创造性的自由,把你的Text小部件换成了Label。正如您所说的,您不熟悉该语言,我非常肯定在这种情况下,LabelText更合适(至少对于这个问题的修复!)。在

另一个建议:当您要多次调用一个函数时(就像我们多次调用moneygain),最好不要在这些函数中创建小部件。当我测试您的代码时,它无限地生成新的Text小部件,因为它被反复调用(同样,可能不是您想要的)。在

Tkinter一开始很难学,但一旦你学会了,它真的很有趣!祝你的项目好运!在

相关问题 更多 >

    热门问题