我正在使用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)
你们可以在这里建议我吗?
答案 0 :(得分:1)
使用self.
refSelect = Button(topFrame, text="Open Reference File",
command=self.refSelect_load_file, bg = "yellow")
修改强>
试试这个。
class Access_all_elements():
def __init__(self):
refSelect = Button(topFrame, text="Open Reference File",
command=lambda:self.refSelect_load_file, bg = "yellow")
refSelect.grid(row =1, column=1)
def refSelect_load_file(self):
self.reffname = askopenfilename(filetypes=(("XML files", "*.xml"),
("All files", "*.*") ))
if self.reffname:
fileOpen = open(self.reffname)
最终修改
from tkinter import *
from tkinter import filedialog
class Access_all_elements():
def __init__(self):
refSelect = Button(root, text="Open Reference File",command=self.refSelect_load_file, bg = "yellow")
refSelect.grid(row =1, column=1)
def refSelect_load_file(self):
self.reffname = filedialog.askopenfilename(filetypes=(("XML files", "*.xml"), ("All files", "*.*") ))
if self.reffname:
fileOpen = open(self.reffname)
root = Tk()
Access_all_elements()
root.mainloop()