Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
115 views
in Technique[技术] by (71.8m points)

python - Tkinter freezes with time

I'm learning Tkinter and at the moment I'm making a dice rolling program, I have encountered a problem where Tkinter freezes, I don't want that to happen as I want the program to have a simple animation where a Label changes from a random number between 1 - 6 and eventually stops giving you the number you rolled.

Here's my code:

import random
import time
from tkinter import *


app = Tk()
app.title("Dice")
app.geometry("200x220")

l1 = Label(app, text=0)
l1.pack()


def randomizer():
    b = 0
    if b < 3:
        a = random.randrange(0, 7, 1)
        time.sleep(0.1)
        l1.config(text=a)
        b += 1


b1 = Button(app, text="Get New Number", command=randomizer)
b1.pack()


app.mainloop()

after method:

import random
from tkinter import *


app = Tk()
app.title("Dice")
app.geometry("200x220")

l1 = Label(app, text=0)
l1.pack()


def change():
    a = random.randrange(1, 7, 1)
    l1.config(text=a)


def time():
    b = 0
    if b < 30:
        app.after(100, change)

        b += 1


b1 = Button(app, text="Get New Number", command=time)
b1.pack()


app.mainloop()

I don't know if the way I used after is correct

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...