由于事件过载,`text.config`崩溃了

问题描述 投票:-3回答:1

我在这里问了这样一个问题:How to adjust Label in tkinter?

但事件加载,最终python无法处理事件,它崩溃了。

怎么让这不发生?也许是因为它处于循环中,所以它们超负荷?我无法弄清楚如何让它不崩溃。

这是我的代码:

from tkinter import *
from time import *
print("""This is an app that basically you time the amount of time someone takes to fall from a cliff, then we will
use an equation to tell you how high the cliff is.
This is a recreation of the app Mark Rober created, by The way""")
window = Tk()
window.title("falling app")
window.geometry("700x700")
window.configure(bg = "sky blue")
"""We will use time import for this"""
mins = 0
seconds = 0
secs = Label(window, text = seconds, font = ("verdana", 60))
secs.place(relx = 0.48, rely = 0.35, anchor = "nw")
def start():
    mins = 0
    seconds = 0
    while seconds != 60:
        sleep(1.00)
        seconds+= 1
        secs.configure(text = seconds)
    if seconds == 60:
        mins = mins+1
        seconds = 0

这一行:secs.configure(text = seconds)是罪魁祸首。我敢肯定。

提前致谢!!!!!!!!

编辑:这就是它的样子,它消隐了,变得反应迟钝。

enter image description here

python-3.x tkinter label
1个回答
0
投票

程序挂起的原因是因为你创建了一个无限循环,阻止tkinter能够处理事件。 Tkinter是单线程的,只有在能够处理稳定的事件流时才能工作。你用这个无限循环阻止了它:

while seconds != 60:
    sleep(1.00)
    seconds+= 1
    secs.configure(text = seconds)

快速解决方法是在该循环中调用update。你的程序仍会冻结一秒钟,然后再激活几毫秒再冻结。这是编写tkinter程序的一种非常低效的方法。

更好的方法是使用after方法连续安排你的函数每秒运行一次。这个网站上可能有数十个不是数百个这种技术的例子。简而言之,它看起来像这样:

def update_clock()
    global mins, seconds
    seconds += 1
    if seconds > 60:
        seconds = 0
        mins += 1
    secs.configure(text = seconds)

    window.after(1000, update_clock)

然后在start方法中调用此函数一次,它将继续每秒运行一次,直到程序退出:

def start():
    global mins, seconds
    mins = 0
    seconds = 0
    update_clock()
© www.soinside.com 2019 - 2024. All rights reserved.