如何在按下按钮时更改Tkinter标签文本 [英] How to change Tkinter label text on button press

查看:667
本文介绍了如何在按下按钮时更改Tkinter标签文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码,它的意思是当按下项目按钮时更改Instruction标签的文本.这不是出于某种原因,我也不完全确定为什么.我试过在press()函数中创建另一个按钮,其名称和参数相同,但文字不同.

I have this code, and its meant to change the text of the Instruction label 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.

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重新分配给新值.

will not affect the label widget. All it will do is reassign the global variable message to a new value.

要更改标签文本,可以使用其 .config()方法(也称为.configure()):

To change the label text, you can use its .config() method (also named .configure()):

def press():
    Instruction.config(text='Button Pressed')


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


In addition, you will need to call the pack method on a separate line when creating the label:

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

否则,会将Instruction分配给None,因为这是该方法的返回值.

Otherwise, Instruction will be assigned to None because that is the method's return value.

这篇关于如何在按下按钮时更改Tkinter标签文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆