TKinter:程序运行时文本小部件不会更新 [英] TKinter: text widget doesn't update while program is runing

查看:22
本文介绍了TKinter:程序运行时文本小部件不会更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,它使用有限元方法进行计算,可能需要几分钟的时间.因为该程序对于用户来说似乎已经冻结,所以我做了它,以便它预先计算将进行的迭代次数,并将进度以百分比形式打印到 TKinter 中的文本小部件.

I have a program that uses finite element methods for calculations that can take up to a couple minutes. Because the program might seem to have frozen for the user, I made it so that it calculates the number of iterations it'll make beforehand, and prints the progress in percentage to a text widget in TKinter.

问题在于程序在迭代时主窗口冻结,只在最后更新文本,这对于用户了解当前的计算进度没有多大用处.

The problem is that the main window freezes while the program is iterating, and only updates the text at the end, which isn't of much use for the user to know the current progress of the calculations.

这是代码的具体部分:

progr+=dcompl
textbox.configure(state=NORMAL)
textbox.delete(1.0,2.0)
textbox.insert(1.0,"Processando... ")
textbox.insert(2.0,str(int(progr))+"%") #the variable progr is the current progress in %
textbox.configure(state=DISABLED)

每次通过代码的特定部分时,它都会更新progr"变量.

It updates the "progr" variable each time it passes through a specific part of the code.

如果我只是将progr"变量打印到控制台,它就可以正常工作,但我希望用户看到的是 UI 而不是控制台.

If I just print the "progr" variable to the console it works just fine, but I expect the user to be looking at the UI and not at the console.

有什么办法可以让 TKinter 窗口在程序运行时不冻结并更新文本?

Is there any way I can make the TKinter window not freeze and update the text while the program is running?

推荐答案

您可以导入 threading 模块并在单独的 threading.Thread<中在后台运行您的数字运算代码/code>,或者您可以导入 subprocess 模块并在一个完全独立的进程中运行它.在必须保留在主线程中的 tkInter 代码中,您将等到线程/子进程向您发送完成的信号并将结果发送给您.(记住不要从后台线程访问任何 tkInter 对象:tkInter 工具包不是线程安全的,这会导致偶发性崩溃.)

You could import the threading module and run your number-crunching code in the background in a separate threading.Thread, or you could import the subprocess module and run it in an entirely separate process. In your tkInter code, which must stay in the main thread, you would wait until the thread/subprocess sends you the signal that it's done and sends you the result. (Remember not to access any tkInter objects from the background thread though: the tkInter toolkit is not thread-safe and this will cause sporadic crashes.)

回应布莱恩的评论:

如何在不占用 CPU 的情况下等待"?我的一些应用程序使用了一个包含 1 毫秒 time.sleep() 的简单循环,结果性能下降并不明显.但是,要正确执行此操作,您可能希望使用 tkinter 对象的 .after() 机制重复调用检查后台数字处理状态的函数.

How do you "wait" without tying up the CPU? Some of my applications have used a simple loop containing a 1-millisecond time.sleep() and the resulting performance hit is not noticeable. However, to do it properly you would probably want to use the tkinter object's .after() mechanism to repeatedly call a function that checks the status of your background number-crunching.

这篇关于TKinter:程序运行时文本小部件不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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