[英]How to change Tkinter label text on button press
I have this code, and its meant to change the text of the Instruction
label when the item button is pressed. 我有这个代码,它意味着在按下项目按钮时更改Instruction
标签的文本。 It doesn't for some reason, and I'm not entirely sure why. 它不是出于某种原因,我不完全确定原因。 I've tried creating another button in the press()
function with the same names and parameters except a different text. 我尝试在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()
Doing: 这样做:
message = 'Button Pressed'
will not affect the label widget. 不会影响标签小部件。 All it will do is reassign the global variable message
to a new value. 它所做的就是将全局变量message
重新分配给新值。
To change the label text, you can use its .config()
method (also named .configure()
): 要更改标签文本,可以使用其.config()
方法 (也称为.configure()
):
def press():
Instruction.config(text='Button Pressed')
In addition, you will need to call the pack
method on a separate line when creating the label: 此外,在创建标签时,您需要在单独的行上调用pack
方法:
Instruction = tkinter.Label(Tk, text=message, font='size, 20')
Instruction.pack()
Otherwise, Instruction
will be assigned to None
because that is the method's return value. 否则, Instruction
将被指定为None
因为这是方法的返回值。
You can make message
a StringVar
to make callback. 您可以使message
成为StringVar
以进行回调。
message = tkinter.StringVar()
message.set('Not pressed.')
You need to set message
to be a textvariable
for Instruction
: 您需要将message
设置为Instruction
的textvariable
:
Instruction = tkinter.Label(Tk, textvariable=message, font='size, 20').pack()
and then 接着
def press():
message.set('Button Pressed')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.