Tkinter - 通过另一个函数

时间:2016-05-04 16:50:56

标签: python-3.x tkinter

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

我编写了以下代码来创建一个简单的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

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

3 个答案:

答案 0 :(得分:2)

//be sure to include track by, major perf gains. <div class="container" ng-repeat="panel in ctrl.panels track by panel.id"> <panel bind="here" ng-if="ctrl.history.length"></panel> </div> 位于MyLabel的本地,因此您无法从main()那样访问它。

如果您不想更改程序的设计,则需要更改ChangeLabelText()的定义,如下所示:

ChangeLabelText()

使用main(),您需要将def ChangeLabelText(m): m.config(text = 'You pressed the button!') 作为参数传递给MyLabel

但是,如果您在声明和定义ChangeLabelText()时对此command = ChangeLabelText(MyLabel)进行编码,则会遇到问题,因为程序将在开始时直接执行MyButton的正文,您将没有预期的结果。

要解决此后期问题,您必须使用(并且可以阅读)lambda

完整程序

所以你的程序变成了:

ChangeLabelText()

演示

点击之前:

enter image description here

点击后:

enter image description here

答案 1 :(得分:1)

但我正在努力保持简单,因为我是Python的新手希望这有助于理解类是简单的方法,否则你必须跳过箍并手动跟踪很多变数。此外,Python样式指南建议将CamelCase用于类名,将lower_case_with_underlines用于变量和函数。 https://www.python.org/dev/peps/pep-0008/

?

答案 2 :(得分:1)

你确定你不想把它作为一个类(我认为它会使你的项目增长时代码更加干净)吗?这是一种实现您所寻找目标的方法:

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


class myWindow:
    def __init__(self, master):
        self.MyLabel = ttk.Label(root, text = 'The button has not been pressed.')
        self.MyLabel.pack()
        self.MyButton = ttk.Button(root, text = 'Press Me', command = self.ChangeLabelText)
        self.MyButton.pack()

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


if __name__ == "__main__": 
    root = Tk()
    mainWindow = myWindow(root)
    root.mainloop()

在Mac中,在按下按钮之前看起来像这样:

enter image description here

当你按下它时:

enter image description here

但基本上,为了能够更改Label或按钮中的文本,您需要确保它具有活动引用。在这种情况下,我们通过将窗口创建为类并以self. widget_name = widget()形式引用窗口小部件来完成此操作。

相关问题