Bhautik Savaliya
Bhautik Savaliya

Reputation: 45

Behavior of after() method inside a for loop in Tkinter GUI

In my sample GUI code, I want to print two different string one after another multiple times. I want some time duration between each string print on the console. I used root.after() method for this and iterate inside 'for loop' to achieve multiple time print. Here is my code.

import tkinter as tk
from tkinter import *

def display1():
    print('hello world!')

def display2():
    print('hello there!')

def print_it():
    for i in range(2):
        root.after(7000,display1)   #to print after seven second.
        root.after(7000+5000,display2)  #to print after five second of first sentence print.

root = tk.Tk()
root.title("testing")
root.geometry('100x100')

btn = tk.Button(root,text='click it',command=print_it)
btn.pack(side = TOP)
root.mainloop()     

The problem is in spite of printing one after another, both strings are printing together and not after a given time. I cannot understand the behavior of the after() method. What am I doing wrong?

Thank you.

Upvotes: 1

Views: 1012

Answers (2)

Bhautik Savaliya
Bhautik Savaliya

Reputation: 45

As per above answer I understood the behavior of root.after() method i.e. In the background, root.after() is added to the event loop, but with the condition that it shouldn't be executed until at least 7 seconds (for this case) from when after() was called. During those 7 seconds, any other events in the queue will be executed first. The command might be executed later than 7 seconds, depending on what's being processed already in the event queue, but no sooner.

Upvotes: 0

Bryan Oakley
Bryan Oakley

Reputation: 386010

Let's look at this code:

def print_it():
    for i in range(2):
        root.after(7000,display1)
        root.after(7000+5000,display2) 

Let's assume that "now" is 12:00.000. When this code runs, the first iteration of the loop will schedule something for 12:07.000, and then another one at 12:12.000. This process maybe takes a millisecond or two. Let's assume it takes 10 milliseconds

The second time through the loop we're now at 12:00.010 since the first iteration took 10ms, so you then schedule something to run at 12:07.010, and then again at 12:12.010.

So now the "after" queue looks like this:

  • display1@12:07.000
  • display1:12:07.010
  • display2@12:12.000
  • display2@12:12.010

It's important to remember that after schedules a job in the future relative to the current moment, not relative to the previous time after was called.

Upvotes: 2

Related Questions