【问题标题】:Capturing thread output to redirect it to GUI(wxpython) in Python捕获线程输出以将其重定向到 Python 中的 GUI(wxpython)
【发布时间】:2019-05-24 15:09:40
【问题描述】:

我有一个内置在 WxPython 中的 GUI。我在同一个 python 脚本中也有一个嵌入 JSON 对象的函数,我想将该函数称为线程(后台进程)

我想捕获该线程的输出,以将其重定向到 GUI 中的多行文本框。

我可以用 subprocess.popen 做到这一点,但现在我想在一个线程中做到这一点,我不能像 subprocess 一样在线程中使用 proca.stdout。 对此的任何帮助将不胜感激。

谢谢! 公关

【问题讨论】:

    标签: python-3.x subprocess python-multithreading wxpython pdal


    【解决方案1】:

    wxpython 要求从主线程调用一些东西。这可以通过调用wx.CallAfterwx.CallLater 或通过创建和发布您自己的自定义事件来完成。 wx.TextCtrl.SetValue 似乎是线程安全的。有几个例子说明如何用 wxpython 实现线程,但这里有另一个例子:

    # tested on windows 10, python 3.6.8
    import wx, threading, time
    
    
    class MainFrame(wx.Frame):
        def __init__(self):
            wx.Frame.__init__(self, None, -1, "Test Frame", wx.DefaultPosition, (500, 500))
            self.tc = wx.TextCtrl(self, -1, "Click button to start thread...", size=(500, 350), style=wx.TE_MULTILINE)
            self.button = wx.Button(self, label="Click to start thread", pos=(0, 360))
            self.button.SetSize(self.button.GetBestSize())
            self.button.CenterOnParent(wx.HORIZONTAL)
    
            self.thread = None
            self.button.Bind(wx.EVT_BUTTON, self.on_button)
            self.Show()
    
        def on_button(self, event):
            self.thread = threading.Thread(target=self.threaded_method)
            self.thread.start()
    
        def threaded_method(self):
            self.tc.SetValue("thread has started.....")
            time.sleep(1.5)
            for n in range(5, 0, -1):
                self.tc.SetValue(f"thread will exit in {n}")
                time.sleep(1)
            self.tc.SetValue("thread has finished")
    
    
    app = wx.App()
    frame = MainFrame()
    app.MainLoop()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-30
      • 1970-01-01
      • 2012-04-24
      • 2018-03-26
      • 1970-01-01
      • 2022-11-11
      • 1970-01-01
      相关资源
      最近更新 更多