为什么这个Python tkinter计时器不起作用 [英] Why doesn't this Python tkinter timer work

查看:245
本文介绍了为什么这个Python tkinter计时器不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在单击按钮后显示为1(等待),2(等待),3(等待)。相反,当我点击按钮时它会停止一秒,而不是它变成3





I want to have to this show up as 1(wait), 2 (wait), 3(wait) after the button is clicked. Instead when I click the button it stops for a second, than it becomes 3


from tkinter import *
from time import *
import tkinter as tk


root = tk.Tk()

root.title("Project")

def clicked1():
    timer = 0
    i = 0
    previous = 0
    while (i < 3):
        previous = previous + 1
        label1.config(text = previous)
        sleep(1)
        i += 1
        
Button1 = tk.Button(root, text = "Click", width = 10, bg = "black",fg = "white", command =clicked1)
Button1.pack(side=TOP)

label1 = tk.Label(root, text = " ", fg = "black",bg = "white")
label1.pack(side = BOTTOM)

root.configure(background="white")
root.geometry("300x600")

root.mainloop()





我尝试了什么:



切换睡眠(1)的位置



What I have tried:

switching around where the sleep(1) is put

推荐答案

这是因为您的睡眠调用会停止尝试更新显示的线程。因此,当显示器显示3时,在睡眠的最后一次退出之前没有任何变化。您需要在一个单独的线程中运行定时器,以便GUI线程在任何数据更改时更新显示。
That is because your sleep call stops the thread that is trying to update the display. So nothing changes until the last exit from the sleep when the display will show 3. You need to run the timer in a separate thread so it allows the GUI thread to update the display when any data changes.


这篇关于为什么这个Python tkinter计时器不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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