gpt4 book ai didi

python - 试图在另一个线程 wxpython 中创建一个对话框

转载 作者:太空狗 更新时间:2023-10-30 01:21:21 25 4
gpt4 key购买 nike

我在另一个线程中运行一个函数,该函数本应填写一个对话框然后显示它,但只要我试图以任何方式更改对话框,它就会出现错误。我读到这是 WxPython 的一个常见问题,开发人员无意直接更改另一个线程中的对话框。

我该如何解决这个问题?我可以只在我的主线程中调用该函数,但这会阻塞我的 GUI,而且初始化对话框是一个冗长的操作 - 我想避免这种情况。

我的代码与下面类似。

在主线程中

# Create the dialog and initialize it
thread.start_new_thread(self.init_dialog, (arg, arg, arg...))

我调用的函数

def init_dialog(self, arg, arg, arg....):
dialog = MyFrame(self, "Dialog")

# Setup the dialog
# ....
dialog.Show()

即使有一个空白对话框和一个简单的调用来在函数内部显示,我也会遇到段错误。非常感谢任何帮助,谢谢。

最佳答案

我做了一个小程序来演示在计算期间保持 GUI 响应并在计算后调用消息框。

    import wx
import threading
import time


class TestFrame(wx.Frame):

def __init__(self):
wx.Frame.__init__(self, None, -1, "I am a test frame")
self.clickbtn = wx.Button(self, label="click me!")
self.Bind(wx.EVT_BUTTON, self.onClick)

def onClick(self, event):
self.clickbtn.Destroy()
self.status = wx.TextCtrl(self)
self.status.SetLabel("0")
print "GUI will be responsive during simulated calculations..."
thread = threading.Thread(target=self.runCalculation)
thread.start()

def runCalculation(self):
print "you can type in the GUI box during calculations"
for s in "1", "2", "3", "...":
time.sleep(1)
wx.CallAfter(self.status.AppendText, s)
wx.CallAfter(self.allDone)

def allDone(self):
self.status.SetLabel("all done")
dlg = wx.MessageDialog(self,
"This message shown only after calculation!",
"",
wx.OK)
result = dlg.ShowModal()
dlg.Destroy()
if result == wx.ID_OK:
self.Destroy()

mySandbox = wx.App()
myFrame = TestFrame()
myFrame.Show()
mySandbox.MainLoop()

GUI 的东西保留在主线程中,而计算继续不受阻碍。根据需要,计算结果在创建对话时可用。

关于python - 试图在另一个线程 wxpython 中创建一个对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31925256/

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