Reputation: 821
I am using Tkinter and trying to call a function within a class, but not getting it to work properly.
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.
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?
Upvotes: 0
Views: 343
Reputation: 534
Your problem will be solved when you call the function using 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()
Upvotes: 1