Reputation: 5
I'm trying to make a simple slot machine python program for an assignment and I am having trouble getting the slot machine images to update. What I want to happen is for the user to click the button and have the three labels dynamically update with a different picture every 0.1 seconds for 2 seconds. But what is happening is my randint is generating random index numbers for the array, but the label only show a new image on the last randint instance. Here is the code I have:
def update_image():
global images
time.sleep(0.1)
y = images[randint(0, 3)]
slot1.delete()
slot1.configure(image = y)
print(y)
def slot_machine():
x = 0
while x != 10:
slot1.after(0,update_image)
x = x + 1
Upvotes: 0
Views: 1849
Reputation: 386230
The problem is that you are calling after(0, ...)
which adds a job to the "after" queue to be run as soon as possible. However, your while loop runs extremely quickly and never gives the event loop the chance to process queued events, so the entire loop ends before a single image changes.
Once the event loop is able to process the events, tkinter will try to process all pending events that are past due. Since you used a timeout of zero, they will all be past due so tkinter will run them all as fast as possible.
The better solution is to have the function that updates the image also be responsible for scheduling the next update. For example:
def update_image(delay, count):
<your existing code here>
# schedule the next iteration, until the counter drops to zero
if count > 0:
slot1.after(delay, update_image, delay, count-1)
With that, you call it once and then it calls itself repeatedly after that:
update_image(100, 10)
Upvotes: 1