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

时间:2016-05-30 08:38:34

标签: python variables tkinter display

我试图每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()

当我尝试显示"平衡"它没有更新。相反,它抛出了这个错误:

Exception in thread Thread-2:
Traceback (most recent call last):

File "D:\Python34\lib\threading.py", line 911, in _bootstrap_inner
    self.run()
  File "D:\Python34\lib\threading.py", line 1177, in run
    self.function(*self.args, **self.kwargs)
  File "D:/Python34/menugui.py", line 27, in moneygain
    text.insert(INSERT, balance)
AttributeError: 'int' object has no attribute 'insert'

如何在Tkinter窗口上显示balance

1 个答案:

答案 0 :(得分:1)

要解决您在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一开始学习起来非常棘手,但是一旦你学会了它,它真的很有趣!祝你的项目好运!