[英]How to get a tkinter Label to update itself?
我有一个标签,我想将其用作计算器的显示 - 当按下按钮时,我希望更新显示。 我正在尝试设置 displayText 所以我应该能够输入 01 或 10。
from tkinter import *
gui = Tk()
buttonValues = []
displayText = StringVar(gui)
def press(buttonValue):
buttonValues.append(buttonValue)
display = Label(gui, text=displayText.set(''.join(str(i) for i in buttonValues)))
display.grid(row=0)
display.update()
"print(''.join(str(i) for i in buttonValues))"
if __name__ == "__main__":
button0 = Button(gui, text=' 0 ', fg='black', bg='red',
command=lambda: press(0), height=1, width=7)
button0.grid(row=2, column=0)
button1 = Button(gui, text=' 1 ', fg='black', bg='red',
command=lambda: press(1), height=1, width=7)
button1.grid(row=2, column=1)
gui.mainloop()
您可以通过将Label
textvariable
选项设置为displayText
字符串变量,然后在需要更改时调用其set()
方法来实现它。 没有必要重复创建一个display
小部件或做任何其他事情——它会自动发生。
from tkinter import *
gui = Tk()
buttonValues = []
displayText = StringVar(value='')
def press(buttonValue):
buttonValues.append(buttonValue)
displayText.set(''.join(map(str, buttonValues)))
if __name__ == "__main__":
display = Label(gui, textvariable=displayText)
display.grid(row=0)
button0 = Button(gui, text=' 0 ', fg='black', bg='red', command=lambda: press(0))
button0.grid(row=2, column=0)
button1 = Button(gui, text=' 1 ', fg='black', bg='red', command=lambda: press(1))
button1.grid(row=2, column=1)
gui.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.