Python 如何在按钮按下时更改 Tkinter 标签文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29828477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:03:30  来源:igfitidea点击:

How to change Tkinter label text on button press

pythonbuttonpython-3.xtkinterlabel

提问by Phoenix

I have this code, and its meant to change the text of the Instructionlabel when the item button is pressed. 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.

我有这个代码,它的目的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()

采纳答案by Phoenix

Doing:

正在做:

message = 'Button Pressed'

will not affect the label widget. All it will do is reassign the global variable messageto 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 packmethod on a separate line when creating the label:

此外,pack在创建标签时,您需要在单独的行上调用该方法:

Instruction = tkinter.Label(Tk, text=message, font='size, 20')
Instruction.pack()

Otherwise, Instructionwill be assigned to Nonebecause that is the method's return value.

否则,Instruction将被赋值,None因为那是方法的返回值。

回答by fdsa

You can make messagea StringVarto make callback.

您可以制作message一个StringVar进行回调。

message = tkinter.StringVar()

message.set('Not pressed.')

You need to set messageto be a textvariablefor Instruction:

您需要设置messagetextvariablefor Instruction

Instruction = tkinter.Label(Tk, textvariable=message, font='size, 20').pack()

Instruction = tkinter.Label(Tk, textvariable=message, font='size, 20').pack()

and then

进而

def press():
    message.set('Button Pressed')