Python 繁忙时如何监控 Tkinter 按钮? [英] How can I monitor Tkinter buttons when Python is busy?

查看:25
本文介绍了Python 繁忙时如何监控 Tkinter 按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Windows XP 上开发 Python 2.7.1/Tkinter 8.4 应用程序,用于检查来自 RS-232 端口的多行输入.但是,如果没有输入到达,它将永远处于循环中.

I am developing a Python 2.7.1 / Tkinter 8.4 app on Windows XP that checks several lines of input from a RS-232 port. However, if no input arrives it will sit in a loop for ever.

我正在尝试在 GUI 上实现放弃测试"按钮,但由于主线程忙于等待输入,因此每次检查是否按下按钮时都不会出现.我试过 update_idletasks() 和 time.sleep(1) 没有成功.

I am trying to implement an ‘Abandon Test’ button on the GUI but because the main thread is busy waiting for input it doesn’t appear to every check if a button has been pressed. I have tried update_idletasks() and time.sleep(1) with no success.

有什么建议吗?

推荐答案

Tk 是单线程的,所以如果主线程很忙,GUI 将冻结.一种解决方案是使用单独的线程进行读取,因此当读取阻塞时,您的主线程可以继续.当您获得一行输入时,您可以将其推送到由主线程监控的队列中.

Tk is single-threaded, so if the main thread is busy the GUI will freeze. One solution is to use a separate thread to do the reading, so when the read blocks your main thread can continue. When you get a line of input you can push it on a queue which is monitored by the main thread.

另一种方法是弄清楚如何在串行端口上进行非阻塞读取.如果有数据,读取它.如果没有,则返回主事件循环.然后,您需要将事件循环配置为每几百毫秒左右轮询一次您的端口,具体取决于您的性能需求.

The other way is to figure out how to do a non-blocking read on your serial port. If there is data, read it. If not, return to the main event loop. You then need to configure the event loop to poll your port every few hundred milliseconds or so, depending on your performance needs.

这篇关于Python 繁忙时如何监控 Tkinter 按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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