通过新线程在Python中打开wx.Frame

时间:2009-08-04 19:42:50

标签: python multithreading wxpython

我有一个框架作为启动屏幕存在,供用户在主程序启动前进行选择。在用户进行选择后,我需要屏幕保持一种闪屏,直到主程序完成加载。

我是通过创建应用程序并启动一个线程来完成的:

class App(wx.App):
    '''
    Creates the main frame and displays it
    Returns true if successful
    '''
    def OnInit(self):
        try:
            '''
            Initialization
            '''
            self.newFile = False
            self.fileName = ""

            self.splashThread = Splash.SplashThread(logging, self)
            self.splashThread.start()
            #...More to the class

启动框架:

class SplashThread(threading.Thread):
    def __init__(self, logger, app):
        threading.Thread.__init__(self)
        self.logger = logger
        self.app = app

    def run(self):
        frame = Frame(self.logger, self.app)
        frame.Show()

需要app值,因为它包含回调,允许主程序在用户进行选择时继续。问题是启动屏幕只闪烁一毫秒然后消失,不允许用户进行选择并阻止其余的启动。

有什么想法吗?提前谢谢!

1 个答案:

答案 0 :(得分:0)

你不需要线程。缺点是启动窗口会在加载时阻塞,但只有当您想要更新它的内容(为其设置动画)或者您希望能够拖动它时才会出现问题。可以通过定期调用wx.SafeYield来解决这个问题。

import time
import wx


class Loader(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)
        sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(sizer)
        self.btn1 = wx.Button(self, label="Option 1")
        self.btn2 = wx.Button(self, label="Option 2")
        sizer.Add(self.btn1, flag=wx.EXPAND)
        sizer.Add(self.btn2, flag=wx.EXPAND)
        self.btn1.Bind(wx.EVT_BUTTON, self.OnOption1)
        self.btn2.Bind(
            wx.EVT_BUTTON, lambda e: wx.MessageBox("There is no option 2")
        )

    def OnOption1(self, event):
        self.btn1.Hide()
        self.btn2.Hide()
        self.Sizer.Add(
            wx.StaticText(self, label="Loading Option 1..."),
            1, wx.ALL | wx.EXPAND, 15
        )
        self.Layout()
        self.Update()
        AppFrame(self).Show()

class AppFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent)
        time.sleep(3)
        parent.Hide()

        # the top window (Loader) is hidden so the app needs to be told to exit
        # when this window is closed
        self.Bind(wx.EVT_CLOSE, lambda e: wx.GetApp().ExitMainLoop())


app = wx.PySimpleApp()
app.TopWindow = Loader()
app.TopWindow.Show()
app.MainLoop()