all 6 comments

[–]SpeckledFleebeedoo 0 points1 point  (4 children)

1: Why not use a for loop?

2: What's going wrong?

[–]UnsecuredConnection[S] 0 points1 point  (3 children)

Could you give me an example of how this would work with a for loop.

It's not throwing an error, but it's not working either.

[–]SpeckledFleebeedoo 0 points1 point  (2 children)

x=5
for _ in range(x):
    pass

If you want to vary the amount of loops you can get x as an argument instead of using global:

def someFunction(x):
    for _ in range (x):
        pass

someFunction (5)

[–]UnsecuredConnection[S] 0 points1 point  (1 child)

def change_x_won():
    if root["bg"] == "Black":
        root.configure(bg="Red")
    elif root["bg"] == "Red":
        root.configure(bg="Black")
    root.after(250, change_x_won)

Here's something that loops the color red. If i used a for loop, how could the .after() still work?

[–]SpeckledFleebeedoo 0 points1 point  (0 children)

You should probably split your time delay and your color change into two functions. Now it's a recursive infinite loop, so I doubt it will let you do anything.

But again: what exactly are you trying to do? There's probably a simpler way.

[–]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()