【发布时间】: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()
使用这段代码有什么问题吗?
【问题讨论】: