freeza
freeza

Reputation: 388

Unexplained Infinite Loop in Tkinter

I am learning Tkinter for python2 where i came across this code.this creates a window in tkinter and increments the value of label every 1 second While the code runs perfectly fine..Can you tell me why an infinite loop is not observed as after every thousand seconds the control return to count() and control should have never reached the last line of code?

import Tkinter as tk

counter = 0 
def counter_label(label):
  def count():
    global counter
    counter += 1
    label.config(text=str(counter))
    label.after(1000, count)
  count()


root = tk.Tk()
root.title("Counting Seconds")
label = tk.Label(root, fg="green")
label.pack()
counter_label(label)
button = tk.Button(root, text='Stop', width=25, command=root.destroy)
button.pack()
root.mainloop()

Also the label variable passed to the function def counter_label is just a copy of original variable so changing it shouldnot affect the original variable.How is it happening?

Any help is appreciated.

Upvotes: 0

Views: 396

Answers (1)

jfs
jfs

Reputation: 414695

  1. 1000 is measured in milliseconds i.e., it is 1 second
  2. count() is reached and it is an infinite loop (if root.mainloop() is running).

label.after(1000, count) schedules count function and returns immediately. The tkinter event loop should be running otherwise count() won't be called again.

Upvotes: 1

Related Questions