1

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.
        """

        self.filepath.set(fd.askopenfilename(initialdir=self._initaldir,
                                                 filetypes=self._filetypes))
        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.

1 Answer 1

1

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?

Sign up to request clarification or add additional context in comments.

1 Comment

If the answer was useful to you, you can accept it by clicking the grey tick mark just under the number and up/down arrows. You can change which answer you have accepted on a question at any time, but you may want to delay accepting one answer in order to encourage other (possibly better) answers. (People are less likely to answer a question which already has an accepted answer.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.