Tkinter freezes with time
This is the proper use of a loop using tkinter:
import random
import tkinter as tk
app = tk.Tk()
app.geometry("200x220")
label = tk.Label(app, text="0")
label.pack()
def change(b=0):
if b < 30:
a = random.randrange(1, 7, 1)
label.config(text=a)
app.after(100, change, b+1)
b1 = tk.Button(app, text="Get New Number", command=change)
b1.pack()
app.mainloop()
The problem with your code is that you scheduled all of the change
calls 100 milliseconds after the button was pressed. So it didn't work.
In the code above I use something like a for loop done using .after
scripts. When calling a function you can add default values for the arguments like what I did here: def change(b=0)
. So the first call to change
is done with b = 0
. When calling .after
you can add parameters that will be passed when the function is called. That is why I used b+1
in app.after(100, change, b+1)
.