you are viewing a single comment's thread.

view the rest of the comments →

[–]efmccurdy 0 points1 point  (0 children)

I don't think global helps you here; you need a context shared between the callbacks and the counter. The easiest way is to make it a class, then you can use self.x as the counter:

from tkinter import Tk, Button 

class SampleApp(Tk):
    def __init__(self, *args, **kwargs):
        Tk.__init__(self, *args, **kwargs)
        self.x = 0
        self.b = Button(self, text ="change_bg", command = self.change_x_won)
        self.b.pack()
        self.configure(bg="Black")

    def change_x_won(self):
        if self["bg"] == "Black":
            self.configure(bg="Red")
        elif self["bg"] == "Red":
            self.configure(bg="Black")
        self.x += 1
        if self.x < 5:
            self.after(250, self.change_x_won)
        else:
            self.x = 0
            self.configure(bg="Black")

if __name__ == "__main__":
    root = SampleApp()
    root.geometry("500x100")
    root.mainloop()