无法将Python类函数作为按钮命令使用

2024-06-28 14:50:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试以下代码:

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()

使用这个代码有什么问题吗


Tags: 代码textselfdefexitbuttonrootlabel
1条回答
网友
1楼 · 发布于 2024-06-28 14:50:32

您不能在类级别上引用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是可行的,但是您只剩下一个与它所在的类无关的静态方法。在这种情况下,将函数保留在全局范围更具python特性:

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()

相关问题 更多 >