简体   繁体   中英

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.

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?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM