Skip to main content
 首页 » 编程设计

python之如何在另一个进程运行时更改 tkinter 标签

2025年05月04日15dyllove98

我有一个很大的代码,按下按钮应该运行大约需要 15 秒才能完成的代码。在这段时间内,我想显示一个标签,上面写着“处理中,请稍候”或类似的东西。但是在 python 中,使用 tkinter 创建的整个 GUI 将在过程结束后卡住和解冻。我该怎么做呢?我创建了一个较小的代码,以便更容易解释。

from tkinter import * 
from threading import Thread 
import os 
import sys 
import time 
 
master = Tk() 
master.geometry("500x500") 
master.resizable(False,False) 
 
def tryout(): 
    sign2.config(text = "AAA") 
    for x in range(5): 
        print(x) 
        time.sleep(1) 
    sign2.config(text = "BBB") 
    for x in range(5): 
        print(x) 
        time.sleep(1) 
    sign2.config(text = "CCC") 
 
def close_window():  
    master.destroy() 
    sys.exit() 
 
sign1 = Label(master, text = "VNA GUI").grid(pady=10, padx=10) 
sign2 = Label(master, text = "Choose option to continue") 
sign2.grid(pady=10, padx=10, ipadx=50) 
Button(master, text='Exit', command=close_window).grid(pady=10, padx=20) 
butTest = Button(master, text='test', command=tryout) 
butTest.grid(pady=10, padx=20) 
 
master.mainloop( ) 

所以在这段代码中,我希望首先在标签上看到“AAA”,然后是从 0 到 4 的计数中间的“BBB”,然后是从 0 到 4 的最终计数末尾的“CCC” 4. 这里发生的是 GUI 在开始时卡住,继续计数,我只看到“CCC”。我该如何解决这个问题?

请您参考如下方法:

使用线程只需进行少量更改即可。

首先创建一个函数start_tryout:

def start_tryout(): 
    Thread(target=tryout, daemon=True).start() # deamon=True is important so that you can close the program correctly 

然后使用新命令创建按钮:

butTest = Button(master, text='test', command=start_tryout) 

然后它应该不再卡住 gui,您应该能够看到标签的变化。