[英]Tkinter calling function in class through class variable
我正在使用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)
你们能在这里建议我吗?
当您使用self.
调用函数时,您的问题将得到解决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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.