我正在尝试以下代码:
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()
使用这个代码有什么问题吗
您不能在类级别上引用
self
,因为对象当时还没有被实例化尝试将这些语句放在
__init__
方法中:虽然从函数参数中删除
self
是可行的,但是您只剩下一个与它所在的类无关的静态方法。在这种情况下,将函数保留在全局范围更具python特性:相关问题 更多 >
编程相关推荐