【问题标题】:Cannot use Python class function as button command不能将 Python 类函数用作按钮命令
【发布时间】:2018-06-23 07:27:27
【问题描述】:

我正在尝试以下代码:

from tkinter import *

root = Tk()

class mainclass():
    def myexit(self):
        exit()
    Label(root, text = "testing").pack()
    Entry(root, text="enter text").pack()
    Button(root, text="Exit",command=self.myexit).pack()

mainclass()
root.mainloop()

运行时出现以下错误:

  File "baseclass_gui.py", line 6, in <module>
    class mainclass():
  File "baseclass_gui.py", line 11, in mainclass
    Button(root, text="Exit",command=self.myexit).pack()
NameError: name 'self' is not defined

如何为按钮命令定义 self?

编辑:

我想把它放在一个类中的原因是:我使用的是 pyreverse,它现在是 pylint 的一部分,它显示了不同类之间的图表关系。它似乎跳过了在主模块级别运行的代码,因此我也想把它放在一个类中。见https://www.logilab.org/blogentry/6883

我发现以下代码有效:

root = Tk()
class mainclass():
    def myexit(): # does not work if (self) is used; 
        exit()
    Label(root, text = "testing").pack()
    Entry(root, text="enter text").pack()
    Button(root, text="Exit",command=myexit).pack()

mainclass()
root.mainloop()

使用这段代码有什么问题吗?

【问题讨论】:

    标签: python class tkinter


    【解决方案1】:

    你不能在类级别上引用self,因为那时对象还没有被实例化。

    尝试将这些语句放在 __init__ 方法中:

    from tkinter import *
    
    root = Tk()
    
    class mainclass():
    
        def myexit(self):
            exit()
    
        def __init__(self):
            Label(root, text = "testing").pack()
            Entry(root, text="enter text").pack()
            Button(root, text="Exit",command=self.myexit).pack()
    
    mainclass()
    root.mainloop()
    

    虽然从函数参数中删除 self 确实有效,但您会得到一个与其所在类无关的静态方法。在这种情况下,将函数留在全局范围内更符合 Pythonic:

    from tkinter import *
    
    root = Tk()
    
    def myexit():
        exit()
    
    class mainclass():
    
        Label(root, text = "testing").pack()
        Entry(root, text="enter text").pack()
        Button(root, text="Exit",command=myexit).pack()
    
    mainclass()
    root.mainloop()
    

    【讨论】:

    • 好答案。请在我上面的问题中查看编辑。添加的新代码可以吗?如果不行,为什么不呢?
    • @rnso 我不会无缘无故地定义一个类。如果你只是要实例化一次来运行你的主程序/循环,那么创建一个类和只在主模块级别运行程序没有区别。
    猜你喜欢
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    相关资源
    最近更新 更多