Python Forum

Full Version: Global Variable in Event Function? What am I doing wrong here?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm using tkinter to create a data entry form, and I'm having issues with getting the state of a checkbutton. So I determined the simplest way is to set a variable, and change that variable each time the checkbutton is clicked. I've tried everything google has suggested for how to do this, and can't seem to get it to work. So, here is what I've gotten so far, but it tells me that I've got an invalid syntax when trying to set the variable as a global variable.

class efs_form():
    def __init__(self):
        # Average Checkbox
        self.efs_chb_var = IntVar()
        self.efs_avg_chb = Checkbutton(self.efs_ef,
                                  text="Include in Average",
                                  variable=self.efs_chb_var,
                                  bg='black',
                                  fg='Light Blue',
                                  selectcolor='black',
                                  font=("Comic Sans MS", 8, "bold"))
        self.efs_avg_chb.grid(row=3, column=1, pady=(20, 10), sticky=W)
        self.efs_avg_chb.select()
        self.my_var = 1
        self.var = self.efs_chb_var.get()
        self.efs_avg_chb.bind("<Button-1>", self.chb_click)
    def chb_click(self, event):
        global self.my_var
        If self.my_var == 1:
            self.my_var = 0
        else:
            self.my_var = 1
        print(self.my_var)
From what I understand (which is very limited), you have to set a variable to global in the function that you are changing the variable. What am I doing wrong here?

I figured this out. I actually don't need to declare the variable as a global variable in the function, and then my "if" statement shouldn't be capitalized. I got it to work just fine now.
Okay well the first mistake is using a Global Variable -- any programmer that has experienced the pain of global variables will tell never use one unless absolutely necessary which means most of the time do not use one no matter how tempting it might seem. Take extra time to figure out how to not make it global as that will save you immense amount of time later on.

To fix your code though delete the entire global statement on line 18 as it is not needed in this context

self. anything declared within the __init__ function causes that variable to be available to the ENTIRE class through out the lifetime of that instance of that class object.

not knowing Tkinter though I cannot speak to your usage of the Checkbutton's Signal and Slot mechanics if after deleting that line if it still does not seem to work I would strongly suggest you looking into your usage of the Checkbutton's event handling syntax -- either that or perhaps a Tkinter aficionado will chime in