【问题标题】:Python: Infinite loop and GUIPython:无限循环和 GUI
【发布时间】:2011-10-28 07:01:46
【问题描述】:
我正在尝试使用 wxPython GUI 编写一个 python 程序。程序必须在后台收集一些信息(无限循环),但此时 GUI 应该处于活动状态。比如,如果我点击某个按钮,某些变量或其他信息必须更改,并且在新的循环中应该使用这个变量而不是旧的。
但我不知道,怎么做。我认为我必须使用线程,但我不明白如何使用它。
任何人都可以建议如何解决这个问题?
提前致谢!
【问题讨论】:
标签:
python
loops
wxpython
infinite
【解决方案1】:
这称为“线程”。使用pythons threading module。
两个例子:
示例 1:
from threading import Thread
class MyCollector(Thread):
def __init__(self, collect_from):
Thread.__init__(self) # must be called !
self.collect_from = collect_from
def run(self):
while True:
# .. collect ur things
collector_thread = MyCollector(my_source_to_collect_from)
collector_thread.start()
# go on with gui
示例 2:
from threading import Thread
def collector(collect_from):
while True:
# .. collect ur things
collector_thread = Thread(target = collector, args = (my_source_to_collect_from,))
collector_thread.start()
# go on with gui
【解决方案3】:
您是否考虑过让 wxPython 定期调用您的事件处理程序,并在其中执行后台处理?当然,这取决于您是否能够将您的工作分成离散的部分。请注意,您的后台处理必须是非阻塞的,以便控制及时返回到 wxPython,以允许响应式 GUI 处理。不确定在 wxPython 中实现这种后台处理的惯用方式是什么,但如果我没记错的话,(Py)Qt 中的技术是使用计时器。