我正在尝试更新tkinter标签和按钮中的信息,而不重新绘制整个屏幕。我使用的是Python 3,Raspberry Pi和Idle。我有一个简单的例子,说明我要做的事情。我在这里看到的评论表明我需要学习操纵stringvariable或IntVar等等,但我的书在这方面完全没有用。在这个例子中,我希望按钮之间的数字跟踪数字的值,因为它随按钮按下而改变。
##MoreOrLess.01.py
from tkinter import *
global number
number = 5
root = Tk()
root.title("Test Buttons")
def Less():
global number
number -= 1
print ("The number is now ", number)
def More():
global number
number += 1
print("The number is now ", number)
def MakeLabel(number):
textvariable = number
label1 = Label(root, text = "Pick a button please.").pack(pady=10)
btnL = Button(root, text = "More", command = More).pack(side = LEFT)
btnR = Button(root, text = "Less", command = Less).pack(side = RIGHT)
label2 = Label(root, text = number).pack(pady = 20)
MakeLabel(number)
答案 0 :(得分:0)
您不仅要自己写一本书,还要查看tkinter的官方documentation。在您的情况下,您必须使用set()
和get()
方法创建IntVar
类型的变量,并且当您想要通过textvariable
链接该变量时。
from tkinter import *
root = Tk()
root.title("Test Buttons")
number = IntVar()
number.set(5)
def Less():
number.set(number.get() - 1)
print ("The number is now ", number.get())
def More():
number.set(number.get() + 1)
print("The number is now ", number.get())
def MakeLabel(number):
textvariable = number
label1 = Label(root, text = "Pick a button please.").pack(pady=10)
btnL = Button(root, text = "More", command = More).pack(side = LEFT)
btnR = Button(root, text = "Less", command = Less).pack(side = RIGHT)
label2 = Label(root, textvariable = number).pack(pady = 20)
MakeLabel(number)
root.mainloop()