【问题标题】:`text.config` crashes because of an overload of events`text.config` 因事件过载而崩溃
【发布时间】:2019-03-25 00:01:21
【问题描述】:

我在这里问了这样一个问题: 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) 是罪魁祸首。我敢肯定。

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

编辑:这就是它的样子,它空白,变得没有响应。

【问题讨论】:

  • 您能否分享minimal reproducible example 以重现该问题?你的函数start如何使用?
  • 您可以使用答案here - 只需将t-=1 替换为t+=1
  • 当它崩溃时,它会做什么?你有错误吗?这真的是您的实际代码吗?我不明白为什么它会导致程序崩溃本身,但它肯定会冻结整整六十秒。
  • @bryan Oakley 它崩溃并说 Windows 正在找出问题所在然后关闭
  • 你的脚本应该很快完成,不会显示任何内容,因为它既不运行 start() 也不运行 mainloop()

标签: python-3.x tkinter label


【解决方案1】:

程序挂起的原因是因为你创建了一个无限循环,它阻止了 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()

【讨论】:

    猜你喜欢
    • 2022-08-24
    • 2014-08-05
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 2011-03-13
    • 2013-03-09
    • 2015-12-08
    相关资源
    最近更新 更多