How To Access Variable Defined Browse Button Class Outside Class Scope

- 1 answer

I have called a class of browse button(to select file location) from main function. This class has browse function to capture file-path variable that stores the path. Now I just want to use this file path defined in class function outside this class like print this variable outside the class scope

I have already tried giving loc as global, other access methods but not of them worked I guess its due to arguments being passed to class.

'''Using Tkinter module'''

class Browse(tk.Frame,object):
    # here __init__ ,_create_widgets,_display_widgets are defined then I have,

    def browse(self):
        """ Browses a .xlsx file or all files and then puts it on the entry.

        print(self.filepath.get()), self      #Path of ATP choosen by user
        loc = self.filepath.get()            #want to excess this out of class

I want to print 'loc' value (able to print inside) outside the the class scope how can I access the same. I guess the problem is being caused due to arguments my class has, though not sure.



As it stands, loc is a local variable in the browse function, and it will cease to exist when the browse function returns. If you write it as:

        self.loc = self.filepath.get()

Then if you have a Browse object called b, you can just write b.loc to access it.

If you want to access the variable even if there is no Browse object to hand, you will need a class variable. Set with:

        Browse.loc = self.filepath.get()

and access with Browse.loc. The problem with class variables is the same as with all global variables though - what if you have two Browse objects? and what if you try to access the class variable from multiple threads?