user-interface - 进入 while 循环时 Tkinter 出现 GUI 问题

标签 user-interface python-3.x tkinter

我有一个简单的 GUI,它从另一个 python 文件运行各种脚本,一切正常,直到 GUI 运行一个包含 while 循环的函数,此时 GUI 似乎崩溃并变得不活动。有谁知道如何克服这个问题,因为我相信这与更新 GUI 有关,谢谢。下面是我的 GUI 的简化版本。

图形用户界面

#!/usr/bin/env python
# Python 3

from tkinter import *
from tkinter import ttk
from Entry import ConstrainedEntry
import tkinter.messagebox
import functions

AlarmCode = "2222"

root = Tk()
root.title("Simple Interface")
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)


ttk.Button(mainframe, width=12,text="ButtonTest", 
           command=lambda: functions.test()).grid(
             column=5, row=5, sticky=SE)

for child in mainframe.winfo_children():
    child.grid_configure(padx=5, pady=5)

root.mainloop()

功能

def test():
    period = 0
    while True:
        if (period) <=100:
            time.sleep(1)
            period +=1
            print(period)
        else:
            print("100 seconds has passed")
            break

上面会发生的是,当循环运行时应用程序将崩溃。如果我在该时间段过后在 else 语句中插入一个中断,一切都会正常工作。我希望用户能够在循环中单击,因为该 GUI 将运行许多不同的功能。

最佳答案

不要在与 Tkinter 代码相同的线程中使用 time.sleep:它会卡住 GUI,直到 test 执行完成。为了避免这种情况,您应该使用 after小部件方法:

# GUI
ttk.Button(mainframe, width=12,text="ButtonTest", 
           command=lambda: functions.test(root))
           .grid(column=5, row=5, sticky=SE)

# functions
def test(root, period=0):
    if period <= 100:
        period += 1
        print(period)
        root.after(1000, lambda: test(root, period))
    else:
        print("100 seconds has passed")

更新:

在您的评论中,您还添加了您的代码不会使用 time.sleep,因此您原来的示例可能不是最合适的。在这种情况下,您可以创建一个新线程来运行您的密集代码。

请注意,我首先发布了 after 的替代方案,因为只有在完全必要的情况下才应使用多线程 - 它会增加应用程序的开销,并增加调试代码的难度。

from threading import Thread

ttk.Button(mainframe, width=12,text="ButtonTest", 
           command=lambda: Thread(target=functions.test).start())
           .grid(column=5, row=5, sticky=SE)

# functions
def test():
    for x in range(100):
        time.sleep(1) # Simulate intense task (not real code!)
        print(x)
    print("100 seconds has passed")

关于user-interface - 进入 while 循环时 Tkinter 出现 GUI 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15602660/

相关文章:

jQuery UI 模式对话框不阻塞

java - CardLayout的卡片显示顺序是随机的吗?

python - 列表理解中的奇怪拆包

python - 为什么嵌套 "yield from"语句(生成器委托(delegate))会产生终止值 `None`?

python - TKinter GUI,如何使帧的大小正确?

tkinter - 无法在 Tkinter 中禁用自动换行

javascript - iOS 7 使用 CSS 的模糊叠加效果?

JAVA。一个按钮可以禁用其他两个按钮,然后单击即可重新启用它们

python - 尝试用 python 更快地渲染 ASCII 艺术

python - 在Tkinter中尝试约会-Python