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

>Solution :

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.

Leave a Reply