如何在另一个进程运行时更改 tkinter 标签? [英] How to change tkinter label while another process is running?

查看:19
本文介绍了如何在另一个进程运行时更改 tkinter 标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的代码,按一下按钮应该运行一个大约需要 15 秒才能完成的代码.在这段时间内,我想显示一个标签,上面写着正在处理,请稍候"或类似的东西.然而,在 python 中,一旦程序结束,使用 tkinter 创建的整个 GUI 将冻结和解冻.我该如何解决这个问题?我创建了一个较小的代码,以便我可以更容易地解释.

I have a large code where a button press is supposed to run a code that will take roughly 15 seconds to complete. Within this time I want to display a label that says "Processing, please wait" or something of that sort. However in python, the whole GUI created using tkinter will freeze and unfreeze once the procedure is over. How do I get around to doing this? I created a smaller code so that I can explain easier.

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".我该如何解决这个问题?

So in this code I expect to see 'AAA' on the label first, followed by 'BBB' at the middle of the count from 0 to 4, and then 'CCC' at the end of the final count from 0 to 4. What happens here is the GUI freezes at the beginning, the count carries on and I just see 'CCC'. How do I get around this?

推荐答案

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

There are only a few changes necessary to do that with threading.

首先创建一个函数start_tryout:

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

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

Then create the button with the new command:

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

然后它应该不再冻结 gui,您应该能够看到标签更改.

Then it should no longer freeze the gui and you should be able to see the label change.

这篇关于如何在另一个进程运行时更改 tkinter 标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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