【发布时间】:2015-07-31 15:36:42
【问题描述】:
我正在使用 Tkinter 并试图在一个类中调用一个函数,但没有让它正常工作。
class Access_all_elements:
def refSelect_load_file(self):
self.reffname = askopenfilename(filetypes=(("XML files", "*.xml"),
("All files", "*.*") ))
if self.reffname:
fileOpen = open(self.reffname)
refSelect = Button(topFrame, text="Open Reference File",
command=lambda:refSelect_load_file(self), bg = "yellow")
refSelect.grid(row =1, column=1)
错误:
在执行上述命令时,按下按钮时出现以下错误:
NameError: global name 'refSelect_load_file' is not defined
我尝试了什么:
我尝试使用 tkinter 的通用方法调用一个对我不起作用的函数。
refSelect = Button(topFrame, text="Open Reference File",
command=refSelect_load_file, bg = "yellow")
refSelect.grid(row =1, column=1)
这引发了我的错误:
TypeError: refSelect_load_file() takes exactly 1 argument (0 given)
你们能在这里给我一些建议吗?
【问题讨论】:
-
在类范围内而不是在类中的方法内创建小部件对我来说似乎很不寻常,例如
__init__。如果你在一个方法中,你可以做command=self.refSelect_load_file。 -
@Kevin 谢谢,我不知道。我现在就试试。
-
@Digvijayad 嘿,我试过了,但是按钮消失了。将整个代码放入
_init_ -
您的代码显示
refSelect_load_file(小写前导“r”),但错误消息显示RefSelect_load_file(大写前导“r”) -
@BryanOakley 感谢您的指点。在我的代码中,类的命名没有正确对齐。我在上一篇文章中被建议为类和函数使用正确的名称结构。所以您看到的错误来自我在代码中使用的名称。对此感到抱歉。虽然我编辑了我的帖子编辑:我现在看到的是你在上一篇帖子中提出的建议:) 谢谢。