[英]Tkinter calling function in class through class variable
I am using Tkinter and trying to call a function within a class, but not getting it to work properly. 我正在使用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)
Error: 错误:
On executing above command, on pressing the button I get following error: 在执行上述命令时,在按下按钮时出现以下错误:
NameError: global name 'refSelect_load_file' is not defined
What I tried: 我试过的
I tried calling a function using tkinter's generic approach which is not working for me. 我尝试使用tkinter的通用方法调用函数,但该方法对我不起作用。
refSelect = Button(topFrame, text="Open Reference File",
command=refSelect_load_file, bg = "yellow")
refSelect.grid(row =1, column=1)
This throws me error: 这引发了我错误:
TypeError: refSelect_load_file() takes exactly 1 argument (0 given)
Can you guys suggest me something here? 你们能在这里建议我吗?
Your problem will be solved when you call the function using self.
当您使用
self.
调用函数时,您的问题将得到解决self.
refSelect = Button(topFrame, text="Open Reference File",
command=self.refSelect_load_file, bg = "yellow")
Edit 编辑
Try this. 尝试这个。
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)
Final Edit 最终编辑
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.