简体   繁体   中英

Use of time.sleep() in Python with Tkinter

I have a small program (a part of a larger project) to show 10 Random numbers with a small delay. The function it self works when I run it in a terminal, BUT when I try to show it in Tkinter it only shows the Random numbers but without the time delay?? (If I use the Button a single random number comes up every time?)


import random, time
import tkinter as tk

window = tk.Tk()
window.title("Cirkus Arcus tidsmaskine!")
window.geometry("800x800")

#---FUNCTIONS----

def  random_number():
    counter = 0      
    while counter<10:
        num = random.randint(1000,3000)         
        num10 = int(num / 10) * 10             
        time.sleep(0.2) 
        counter = counter + 1          
        return (num10)

---DISPLAYS----

def number_display2():
    randomNumber = random_number()

    # This creates a text field
    number_display2 = tk.Text(master=window, height=10, width=30)
    number_display2.grid(column=0, row=4)
    number_display2.insert(tk.END, randomNumber)

---BUTTONS----

button2 = tk.Button(text="Prøv også mig", command=number_display2)
button2.grid(column=1, row=2)

window.mainloop()

The using of time.sleep() blocks the program.

The definition of time.sleep() in the documentation it's :

Suspend execution of the calling thread for the given number of seconds.

If you want to delay in Tkinter you can use the after() method,

.after(delay, callback=None) is a method defined for all tkinter widgets. This method simply calls the function callback after the given delay in ms. If no function is given, it acts similar to time.sleep (but in milliseconds instead of seconds)

You have to use :

window.after(10000)  # 10000 means 10s

I would advise using the "after" method when it comes to Tkinter. There have been several other questions regarding this topic. Please note that the delay is in milliseconds instead of the seconds used in time.sleep()

import tkinter as tk
import random
root=tk.Tk()
def random_number():
    counter = 0   
    while counter<10:
       num = random.randint(1000,3000)         
       num10 = int(num / 10) * 10             
       print(counter)
       print(num10)
       counter = counter + 1
    return(num10)
root.after(2000,random_number)
root.mainloop()

This works but my kernel keeps running after it finishes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM