gpt4 book ai didi

python-3.x - Tkinter - 通过另一个功能更改标签文本

转载 作者:行者123 更新时间:2023-12-04 02:15:43 25 4
gpt4 key购买 nike

我知道使用面向对象编程 (OOP) 编写 Tkinter GUI 代码通常是 best practice,但我试图保持简单,因为我是 Python 的新手。

我编写了以下代码来创建一个简单的 GUI:

#!/usr/bin/python3
from tkinter import *
from tkinter import ttk

def ChangeLabelText():
MyLabel.config(text = 'You pressed the button!')

def main():
Root = Tk()
MyLabel = ttk.Label(Root, text = 'The button has not been pressed.')
MyLabel.pack()
MyButton = ttk.Button(Root, text = 'Press Me', command = ChangeLabelText)
MyButton.pack()
Root.mainloop()

if __name__ == "__main__": main()

The GUI looks like this.

我认为 GUI (MyLabel) 中的文本会更改为“您按下了按钮!”单击按钮时,但单击按钮时出现以下错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\elsey\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args)
File "C:/Users/elsey/Documents/question code.py", line 6, in ChangeLabelText
MyLabel.config(text = 'You pressed the button!')
NameError: name 'MyLabel' is not defined

我究竟做错了什么?任何指导将不胜感激。

最佳答案

MyLabelmain() 本地的,因此您无法从 ChangeLabelText() 以这种方式访问​​它。

如果你不想改变程序的设计,那么你需要像下面这样改变 ChangeLabelText() 的定义:

def ChangeLabelText(m):
m.config(text = 'You pressed the button!')

使用 main() 您需要将 MyLabel 作为参数传递给 ChangeLabelText()

但是同样,如果你在声明和定义 command = ChangeLabelText(MyLabel) 时编写这个 MyButton 就会有问题,因为程序会在开始时直接执行 ChangeLabelText() 的主体,你不会得到想要的结果。

要解决这个稍后的问题,您将不得不使用(并且可能会阅读) lambda

完整程序

所以你的程序变成:
#!/usr/bin/python3
from tkinter import *
from tkinter import ttk

def ChangeLabelText(m):
m.config(text = 'You pressed the button!')

def main():
Root = Tk()
MyLabel = ttk.Label(Root, text = 'The button has not been pressed.')
MyLabel.pack()
MyButton = ttk.Button(Root, text = 'Press Me', command = lambda: ChangeLabelText(MyLabel))
MyButton.pack()
Root.mainloop()

if __name__ == "__main__":
main()

演示

点击前:

enter image description here

点击后:

enter image description here

关于python-3.x - Tkinter - 通过另一个功能更改标签文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37033709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com