如何在按下按钮时更改Tkinter标签文本
问题内容:
我有这段代码,它的目的Instruction
是在按下项目按钮时更改标签的文本。这不是出于某种原因,我也不完全确定为什么。我试过在press()
函数中创建另一个按钮,它们具有相同的名称和参数,但文字不同。
import tkinter
import Theme
import Info
Tk = tkinter.Tk()
message = 'Not pressed.'
#Sets window Options
Tk.wm_title(Info.Title)
Tk.resizable(width='FALSE', height='FALSE')
Tk.wm_geometry("%dx%d%+d%+d" % (720, 480, 0, 0))
#Method run by item button
def press():
message = 'Button Pressed'
Tk.update()
#item button
item = tkinter.Button(Tk, command=press).pack()
#label
Instruction = tkinter.Label(Tk, text=message, bg=Theme.GUI_hl2, font='size, 20').pack()
#Background
Tk.configure(background=Theme.GUI_bg)
Tk.mainloop()
问题答案:
正在做:
message = 'Button Pressed'
不会影响标签小部件。它要做的就是将全局变量重新分配message
给新值。
要更改标签文本,可以使用其.config()
方法(也称为.configure()
):
def press():
Instruction.config(text='Button Pressed')
另外,pack
创建标签时,您需要在另一行上调用该方法:
Instruction = tkinter.Label(Tk, text=message, font='size, 20')
Instruction.pack()
否则,Instruction
将被分配给它,None
因为那是方法的返回值。