Tkinter 随时间冻结 [英] Tkinter freezes with time

查看:26
本文介绍了Tkinter 随时间冻结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Tkinter,目前我正在制作一个掷骰子程序,我遇到了 Tkinter 冻结的问题,我不希望这种情况发生,因为我希望程序有一个简单的动画,其中Label 从 1 到 6 之间的随机数变化,最终停止为您提供滚动的数字.

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.

这是我的代码:

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 方法:

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

推荐答案

这是使用 tkinter 正确使用循环的方法:

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

您的代码的问题在于您在按下按钮 100 毫秒后安排了所有 change 调用.所以它没有用.

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.

在上面的代码中,我使用了类似于使用 .after 脚本完成的 for 循环.调用函数时,您可以像我在这里所做的那样为参数添加默认值:def change(b=0).所以对 change 的第一次调用是通过 b = 0 完成的.在调用 .after 时,您可以添加将在调用函数时传递的参数.这就是我在 app.after(100, change, b+1) 中使用 b+1 的原因.

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

这篇关于Tkinter 随时间冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆