Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use a variable in __init__ in another function (Python)

I am trying to use var1, which is the variable for a Tkinter Checkbutton in another function but I keep getting a Type Error which I am assuming is a result of var1 being a local scope in init. Normally, I would just return the var1 value (in order to use it in another function) but in the case that it is used in an init function I am not sure what to do.

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        var1 = tk.IntVar() # <-- local var1 variable
        self.include_subf = ttk.Checkbutton(self, text="Include subfolders", variable=var1,
                                            onvalue=1, offvalue=0)

    def a_function(self):
        if var1.get() == 1: # <-- want to use var1 here
            pass

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is exactly what a class is for. Rather than saving the value into a local variable var1 save it as an attribute (a variable belonging to the class instance across its entire lifespan) with self.var1 = .... Then you can access it in all the other instance methods with self.var1.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading