簡體   English   中英

Python:無限循環和 GUI

[英]Python: Infinite loop and GUI

我正在嘗試使用 wxPython GUI 編寫 python 程序。 程序必須在后台收集一些信息(無限循環),但此時 GUI 應該處於活動狀態。 就像,如果我單擊某個按鈕,某些變量或其他信息必須更改,並且在新的循環中應該使用這個變量而不是舊的。

但是不知道怎么弄我認為我必須使用線程,但我不明白如何使用它。

任何人都可以建議如何解決這個問題?

提前致謝!

您肯定需要使用線程來完成此操作。 然后當你從非 GUI 線程獲取一些數據時,你可以使用 wxPython 的線程安全方法之一讓它知道它需要更新。 這是一個小教程: http://www.blog.pythonlibrary.org/2010/05/22/wxpython-and-threads/

或者常年的最愛: http://wiki.wxpython.org/LongRunningTasks

另一種方法是使用 Python 的 socket 模塊創建一個套接字服務器並以這種方式與 wx 通信。

這稱為“線程”。 使用pythons 線程模塊

兩個例子:

示例 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

您是否考慮過讓 wxPython 定期調用您的事件處理程序,並在其中執行后台處理? 當然,這取決於您是否能夠將您的工作分成離散的部分。 請注意,您的后台處理必須是非阻塞的,以便控制及時返回到 wxPython,以允許響應式 GUI 處理。 不確定在 wxPython 中實現此類后台處理的慣用方式是什么,但如果我沒記錯的話,(Py)Qt 中的技術是使用計時器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM