gpt4 book ai didi

python - wxPython:在其他线程中执行某些操作时显示框架

转载 作者:太空宇宙 更新时间:2023-11-03 18:24:53 24 4
gpt4 key购买 nike

在我的带有 wxPython 的 GUI 中,如果必须进行一些计算,这可能需要一些时间。因此,我想在单独的线程中启动它们,并在 GUI 中显示一个窗口,打印程序正在计算的信息。在此期间应禁用主窗口。这就是我的代码:

import time
import threading

import wx

def calculate():
# Simulates the calculation
time.sleep(5)
return True

class CalcFrame(wx.Frame):

def __init__(self, parent, id):
wx.Frame.__init__(self, parent=None, id=-1, title="Calculate")
# Normally here are some intctrls, but i dont show them to keep it easy
self.panel = wx.Panel(parent=self, id=-1)
self.createButtons()

def createButtons(self):
button = wx.Button(parent=self.panel, id=-1, label="Calculate")
button.Bind(wx.EVT_BUTTON, self.onCalculate)

def onCalculate(self, event):
calcThread = threading.Thread(target=calculate)
checkThread = threading.Thread(target=self.checkThread, args=(calcThread,))
self.createWaitingFrame()
self.waitingFrame.Show(True)
self.Disable()
calcThread.run()
checkThread.run()

def createWaitingFrame(self):
self.waitingFrame = wx.MiniFrame(parent=self, title="Please wait")
panel = wx.Panel(parent=self.waitingFrame)
waitingText = wx.StaticText(parent=panel, label="Please wait - Calculating", style=wx.ALIGN_CENTER)

def checkThread(self, thread):
while thread.is_alive():
pass
print "Fertig"
self.waitingFrame.Destroy()
self.Enable()

app = wx.PySimpleApp()
frame = CalcFrame(parent=None, id=-1)
frame.Show()
app.MainLoop()

但我现在的问题是,如果我按“计算”按钮, waitingFrame 不会正确显示,我看不到文本。我也无法移动/最大化/最小化主窗口。你能帮助我吗?预先感谢您:)

最佳答案

你永远不应该在主线程以外的线程中更新GUI....我很确定wxPython的文档在几个地方提到了这一点..它不是线程安全的并且你的GUI会处于损坏状态...

相反,我相信你应该做类似的事情

def thread1():
time.sleep(5)
return True

def thread2(t1,gui):
while thread.is_alive():
pass
print "Fertig"
wx.CallAfter(gui.ThreadDone)

class MyFrame(wx.Frame):
def startThread(self):
calcThread = threading.Thread(target=thread1)
checkThread = threading.Thread(target=thread2, args=(calcThread,self))
def ThreadDone(self):
print "Both threads done???"
print "Now modify gui from main thread(here!)"

关于python - wxPython:在其他线程中执行某些操作时显示框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23392544/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com