简体   繁体   中英

wxPython launches my app twice when importing a sub-package

I'm sorry for the verbal description.

I have a wxPython app in a file called applicationwindow.py that resides in a package called garlicsimwx . When I launch the app by launching the aforementioned file, it all works well. However, I have created a file rundemo.py in a folder which contains the garlicsimwx package, which runs the app as well. When I use rundemo.py , the app launches, however, when the main wx.Frame imports a sub-package of garlicsimwx , namely simulations.life , for some reason a new instance of my application is created (ie, a new identical window pops out.)

I have tried stepping through the commands one-by-one, and although the bug happens only after importing the sub-package, the import statement doesn't directly cause it. Only when control returns to PyApp.MainLoop the second window opens.

How do I stop this?

I think you have code in one of your modules that looks like this:

import wx

class MyFrame(wx.Frame):
    def __init__(...):
       ...

frame = MyFrame(...)

The frame will be created when this module is first imported. To prevent that, use the common Python idiom:

import wx

class MyFrame(wx.Frame):
    def __init__(...):
       ...

if __name__ == '__main__':
    frame = MyFrame(...)

Did I guess correctly?

You could create a global boolean variable like g_window_was_drawn and check it in the function that does the work of creating a window. The value would be false at the start of the program and would change to True when first creating a window. The function that creates the window would check if the g_window_was_drawn is already true, and if it is, it would throw an exception. Then You will have a nice stacktrace telling You who is responsible of executing this function.

I hope that helps You find it. I'm sorry for the verbal solution ;)

Got it: There was no

if __name__=='__main__':

in my rundemo file. It was actually a multiprocessing issue: The new window was opened in a separate process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM