wxPython: call a wxApp from another wxApp - python

Is it possible to run a wxApp from another wxApp?
I am trying to simply call a program I wrote (called DataDeck) from a method of another wxApp, like it was a plugin.
something like:
def on_datadeck_btn_click(self, event):
import datadeck.main
datadeck.main.run()
event.Skip()
where datadeck.main.run() is a classic start of a wxApp:
def run():
app = DataDeck(0)
app.SetAppName("DataDeck")
app.MainLoop()
Right now, it correctly opens DataDeck the first time and it works, but it won't reopen DataDeck a second time after I close it. This would freeze everything.
Update: based on #Mike Driscoll answer, I documented myself more and came to the following solution:
I added an "entry point" in datadeck
def run_as_plugin():
#[do some stuff related to XRC layouts and sysout redirection]
MainGUI = datadeck.gui.maingui.MainGUI()
Where the constructor of MainGUI() automatically shows the wxFrame. Now my application behaves like it was a component of the caller wxApp.
Therefore, I modify the application method as follows:
def on_datadeck_btn_click(self, event):
import datadeck.main
datadeck.main.run_as_plugin()
event.Skip()
It was very simple, indeed! I just had to modify my objects that deal with stdout redirection (not part of this question, I omit the details), and everything worked fine.

There should only be on wx.App. From what I've read online, you can't have two wx.App objects running in one script. You could probably do it using the subprocess module to open a new process though. Take a look at Editra to see some examples for how to do plugins. It is included with wxPython or you can download it separately.

It is perfectly feasible. Not sure why it doesnt work for you.
This example works perfectly:
--main.py--
import wx
class MainFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, title='Main', size=(353,270))
button= wx.Button(self, -1, 'call app', pos=(10,10), size=(-1,30))
self.Bind(wx.EVT_BUTTON, self.capp, button)
def capp(self, event):
import datadeck
datadeck.run()
if __name__ == '__main__':
app = wx.App(0)
frame = MainFrame(None)
frame.Show()
app.MainLoop()
--datadeck.py--
import wx
class DDFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, title='DDFrame', size=(353,270))
button = wx.Button(self, -1, 'print something', pos=(100,100), size=(-1,30))
self.Bind(wx.EVT_BUTTON, self.say_hello, button)
def say_hello(self, event):
print 'something'
class DataDeck(wx.App):
def OnInit(self):
frame = DDFrame(None)
frame.Show()
return True
def run():
app = DataDeck(1)
app.SetAppName("DataDeck")
app.MainLoop()
if you press the 'call app' button you get the new frame open. And you can open as many as you want.
Created aplications/frames are independent of each other. You can close any of them without affecting the others. And the system doesnt freeze.

Related

binding packages with wxpython

I'm kind of new with wxpython and python itself, sorry for the basic question.
I'm trying to organize my code in a more easy way to manage it. I created this simple example that kind of resume my problem. Basically it is just a window with a button that print a message. I separated it in three simple packages
ef_Main.py - This is the main packages it will import the UI and the application itself.
ef_Tool.py - it is the application that will run all the important code, right now it is just a print statment but will have all the application code.
ef_UI.py - a very basic interface using wxpython.
How it should work:
Run ef_Main.py it will import the interface (ef_UI.py) and the main code (ef_Tool.py). When something is click in the interface it will be ready by the ef_Main and send to ef_Tool to be executed.
My problem is:
I'm not sure how to use bind function to connect this three packages. I believe that it should be in the ef_Main but how it will get the info from the interface and send it to the ef_Tool.py.
And if I want to get some output from the ef_Tool and send it back to the interface. How should I do that.
Here is my code.
#ef_Main.py
import wx
import ef_UI as eU
import ef_Tool as eT
''' Here is where I don't know how to make it works,
if I should put a class here or not, and how to bind
this function with the impTool and impUI'''
#class MyMain(self):
def uiControls(self):
self.Bind(wx.EVT_BUTTON, eU.OnClick(self), eT.MyTools(self))
def main():
app = wx.App(False)
frame = eU.MyFrame()
frame.Show()
app.MainLoop()
if __name__ == "__main__":
main()
=======================
#ef_Tool.py
import wx
'''just a simple as possible function to be execute when it is called '''
class MyTools():
def OnClick(self, event):
#Value = self.MyTextCtrl.GetValue()
print "it is working! "
=======================
#ef_UI.py
import wx
''' very simple interface with only a button and a TextCtrl '''
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Menu Test")
self.panel = wx.Panel(self)
self.MyButton = wx.Button(self.panel, -1, "Button_test", (0, 0))
self.MyTextCtrl = wx.TextCtrl(self.panel, -1, value="just a test", pos=(100, 0))
Thanks in advance!
Emerson
Here is a simple example of fulfilling your requirements. Supposing all your application logic is done in ef_Tool.py and the input for these logic is from ef_UI and the output is also sent to ef_UI.py.
You need to call a method in ef_Tool.py when a button click event occurs in ef_UI. You can invoke this method from MyFrame's method. But you need an obj of MyTools to do this.
so first, create an obj for MyTools in ef_Main.py and pass this object to MyFrame
#ef_Main.py
import wx
import ef_UI as eU
import ef_Tool as eT
def main():
efToolObj = eT.MyTools() # object of MyTools class
app = wx.App(False)
frame = eU.MyFrame(efToolObj) # Pass this to MyFrame so that it can make use of it
frame.Show()
app.MainLoop()
if __name__ == "__main__":
main()
Store this MyTools's object in you MyFrame class. And then use this object to call the corresponding method inside MyTools
#ef_UI.py
import wx
''' very simple interface with only a button and a TextCtrl '''
class MyFrame(wx.Frame):
def __init__(self, efToolObj):
wx.Frame.__init__(self, None, title="Menu Test")
self.panel = wx.Panel(self)
self.efToolObj = efToolObj # save the MyTools object to be used later
self.MyButton = wx.Button(self.panel, -1, "Button_test", (0, 0))
self.MyButton.Bind(wx.EVT_BUTTON, self.onClickEvent) # Bind the click event to an event handling method
self.MyTextCtrl = wx.TextCtrl(self.panel, -1, value="just a test", pos=(100, 0))
def onClickEvent(self,event): #this is called when a button is clicked
res = self.efToolObj.OnClickPrinting(self.MyTextCtrl.GetValue()) #Use the mytools object to call its method to apply logic,also get result values
self.MyTextCtrl.SetValue(res) #use the result values in your UI
You can pass the info you want to send to the application logic in its arguments and get results as return values.
#ef_Tool.py
class MyTools:
def OnClickPrinting(self,textvalue):
#Value = self.MyTextCtrl.GetValue()
print "it is working! ",textvalue
resultstr = "test successful"
return resultstr
Hope this helped.

wxpython unittest with modal dialog

I have a wxPython GUI, and I am attempting to use unittest to test some of my modal dialogs. I tried to follow the example given here (you have to scroll down to the bottom of the page): http://wiki.wxpython.org/Unit%20Testing%20with%20wxPython, but it does not work for me. It simply freezes in the middle.
I've adapted the code from the wiki to this:
btn_id = wx.NewId()
class MyDialog(wx.Dialog):
def __init__(self, parent):
wx.Dialog.__init__(self, parent, -1, 'Test')
self.btn = wx.Button(self, btn_id, label="OK!!")
self.btn.Bind(wx.EVT_BUTTON, self.close_dialog)
def close_dialog(self, event):
print 'close me'
class TestMyDialog(unittest.TestCase):
def setUp(self):
self.app = wx.App()
self.frame = wx.Frame(None)
self.frame.Show()
def tearDown(self):
wx.CallAfter(self.app.Exit)
self.app.MainLoop()
def testDialog(self):
def clickOK():
clickEvent = wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, btn_id)
self.dlg.ProcessEvent(clickEvent)
print 'finished clickOK'
wx.CallAfter(clickOK)
self.ShowDialog()
def ShowDialog(self):
self.dlg = MyDialog(self.frame)
self.dlg.ShowModal()
self.dlg.Destroy()
if __name__ == '__main__':
unittest.main()
To my understanding, what should happen is that ShowDialog is called, then gets 'stuck' on ShowModal, at which time clickOk should run (called by wx.CallAfter). This seems to happen, but for some reason the click event isn't actually processed, and the tests hangs. When I run MyDialog not in testing the event binding works fine and the dialog closes when the Ok button is clicked.
I shouldn't need app.mainloop() to be able to ProcessEvent, right? What is going on here?
Have a look at the unittests in Phoenix https://github.com/wxWidgets/Phoenix , look at test_dialog.py and the base staff in wtc.py

wxPython fails to quit

My wxPython GUI either quits with a Segmentation Fault or fails to quit at all using the standard options. The only successful quit option (no errors) is wx.Exit, which I understand is not a great practice. I've traced the issues down to a few factors, but I'm scratching my head as to why they are having this effect.
Using the wxPython inspector (wx.lib.inspection.InspectionTool()), I've been able to determine that a FigureFrameWxAgg is being created when I run certain pylab functions (pylab.xticks() is the function that creates it here, but I haven't tracked down every single function that has this effect). I don't know what this window is for. It's invisible and doesn't appear to do anything. However, this window totally messes up the shutdown of my GUI. If I use self.Destroy, Python doesn't shut down fully. If I use sys.exit, I get a Segmentation fault. I need to catch the wx.EVT_CLOSE so that I can prompt the user to save his/her work.
Here is the code for a simplified version of the GUI:
import matplotlib
matplotlib.use('WXAgg')
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigCanvas
import wx
import wx.grid
import wx.lib.scrolledpanel
import wx.lib.inspection
import sys
import pylab
class my_frame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Many Rows')
self.InitUI()
def InitUI(self):
self.panel = wx.Window(self, size=(200, 200))
hbox_all= wx.BoxSizer(wx.HORIZONTAL)
self.create_menubar()
self.fig1 = pylab.Figure((5, 5), dpi=100)
self.canvas1 = FigCanvas(self.panel, -1, self.fig1)
self.fig1.text(0.01,0.98,"Arai plot",{'family':'Arial', 'fontsize':10, 'style':'normal','va':'center', 'ha':'left' })
self.araiplot = self.fig1.add_axes([0.1,0.1,0.8,0.8])
self.araiplot.clear()
self.araiplot.plot(range(5),range(5),lw=0.75,clip_on=False)
xt = pylab.xticks()
grid = wx.grid.Grid(self.panel)
grid.ClearGrid()
grid.CreateGrid(100, 100)
grid.AutoSize()
hbox_all.AddSpacer(self.canvas1)
hbox_all.AddSpacer(20)
hbox_all.AddSpacer(grid)
hbox_all.AddSpacer(20)
self.panel.SetSizer(hbox_all)
hbox_all.Fit(self)
self.Centre()
self.Show()
def create_menubar(self):
"""
Create menu bar
"""
self.menubar = wx.MenuBar()
menu_file = wx.Menu()
menu_file.AppendSeparator()
m_exit = menu_file.Append(wx.ID_EXIT, "Quit", "Quit application")
self.Bind(wx.EVT_CLOSE, self.on_menu_exit)
self.menubar.Append(menu_file, "&File")
self.SetMenuBar(self.menubar)
def on_menu_exit(self, event):
self.Destroy() # this doesn't quit Python fully, unless I comment out 'matplotlib.use('WXAgg')'
#for w in wx.GetTopLevelWindows():
# if w.Title == 'Figure 1':
# w.Destroy() # if I pre-destroy the FigureFrameWxAgg window, I get a PyDeadObjectError when I run self.Destroy
# self.Destroy() #
# wx.Exit() # forces the program to exit, with no clean up. works, but not an ideal solution
#sys.exit() # program closes, but with segmentation error
#self.Close() # creates infinite recursion error, because we have a binding to wx.EVT_CLOSE
if __name__ == '__main__':
app = wx.PySimpleApp(redirect=False)
app.frame = my_frame()
if '-i' in sys.argv:
wx.lib.inspection.InspectionTool().Show()
app.MainLoop()
To add one more level of complexity, the Segmentation Fault with sys.exit() only happens with my brew installed Python. Sys.exit() works fine with Canopy Python.
My questions are: how can I fix this error? And, is using wx.Exit() really so bad?
There are several issues with your example:
Do not use pylab in GUI applications, because is brings its own mainloop (which will not quit when the wxPython mainloop quits). You had to kill pylab.
# both not required
# matplotlib.use('WXAgg')
# import pylab
# use instead
from matplotlib.figure import Figure
...
def __init__(# ...
...
self.fig1 = Figure((5, 5), dpi=100)
Your menu item "Close" does not work (at least not on Windows). wx.ID_EXIT is meant for buttons in dialogs. Do not ask me which predefined IDs are meant for menus.
ID_QUIT = wx.NewId()
menu_file.Append(ID_QUIT , "Quit", "Quit application")
#
self.Bind(wx.EVT_MENU, self.on_quit, id=ID_QUIT)
def on_quit(self, evt):
self.Close()
In this case it is not necessary to bind to wx.EVT_CLOSE. If you want to do something on the close event, you have to skip it. When you skip it, wxPython will deal with it on its own.
self.Bind(wx.EVT_CLOSE, self.on_close)
...
def on_close(self, evt):
# you can veto the close here or perform cleanup
evt.Skip()
If you change your code accordingly, wxPython will close everything properly.
I agree with the answer from #nepix32 on not using pylab but use the OOP approach of Matplotlib. However, in my case, I still need the matplotlib.use('WX') for the application to show.
I have the same problem of wxpython GUI application not terminated properly if a Matplotlib figure is displayed even if I'm not using pylab or pyplot.
My workaround is to pass the app object to the wx.Frame class and call app.Exit at EVT_CLOSE.
class my_frame(wx.Frame):
def __init__(self, app=None):
...
self.InitUI()
self.Bind(wx.EVT_CLOSE, lambda evt: app.Exit())
...
if __name__ == '__main__':
...
app.frame = my_frame(app)
...
I am up for anyone who can suggest cleaner solution. To be honest, I'm still new to wxpython.

showing another window/frame in wxPython

I am fairly new to programming and to python and wxpython. I have looked over this code for literally HOURS and I tried finding an answer everywhere online. I am having trouble getting a new window to show up after a menu item is clicked. Here is my code so far...
import wx
class MainWindow(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self,parent,id,'Python Test App',size=(600,400))
panel=wx.Panel(self)
wx.Frame.CenterOnScreen(self)
##wx.Frame.Maximize(self)
status=self.CreateStatusBar()
menubar=wx.MenuBar()
file_menu=wx.Menu()
edit_menu=wx.Menu()
ID_FILE_NEW = 1
ID_FILE_OPEN = 2
ID_EDIT_UNDO = 3
ID_EDIT_REDO = 4
file_menu.Append(ID_FILE_NEW,"New Window","This is a new window")
file_menu.Append(ID_FILE_OPEN,"Open...","This will open a new window")
edit_menu.Append(ID_EDIT_UNDO,"Undo","This will undo your last action")
edit_menu.Append(ID_EDIT_REDO,"Redo","This will redo your last undo")
menubar.Append(file_menu,"File")
menubar.Append(edit_menu,"Edit")
self.SetMenuBar(menubar)
self.Bind(wx.EVT_MENU, NewWindow.new_frame, None, 1)
class NewWindow(wx.Frame):
def __init__(self,MainWindow,id):
wx.Frame.__init__(self, None, id, 'New Window', size=(600,400))
wx.Frame.CenterOnScreen(self)
self.Show(False)
def new_frame(self, event):
NewWindow.Show(True)
if __name__=='__main__':
app=wx.PySimpleApp()
frame=MainWindow(parent=None,id=-1)
frame.Show()
app.MainLoop()
When I try to run this code, I get this error message once I click on the menu item "New Window"
TypeError: unbound method new_frame() must be called with NewWindow instance as first argument (got CommandEvent instance instead)
Again, I am fairly new to programming. Any help is greatly appreciated and also, I know my code may not be the "cleanest" looking code around. Thanks in advance!
You don't seem to understand how classes work in Python. You try to call NewWindow.new_frame, but you never actually create an instance of that class.
The error message is because you are calling the method on the class instead of on an instance of the class. What you want to do is something like:
newWin = NewWindow(...) # replace ... with the appropriate parameters
newWin.Show(True)
You don't provide enough information in your example to know what the appropriate parameters are for the NewWindow call (e.g., you don't show where you create the main window), but the MainWindow and id parameters in NewWindow.__init__ aren't just there for looks: wxPython needs to know the parent window. You should look into the wxPython documentation to understand how to create a wxFrame.
Modifying your code to some extent i was able to show a new window when user clicks a New Window option,
Do check the stuff that i have modified a let me know if this is what you want??
import wx
class MainWindow(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self,parent,id,'Python Test App',size=(600,400))
panel=wx.Panel(self)
wx.Frame.CenterOnScreen(self)
status=self.CreateStatusBar()
menubar=wx.MenuBar()
file_menu=wx.Menu()
edit_menu=wx.Menu()
ID_FILE_NEW = 1
ID_FILE_OPEN = 2
ID_EDIT_UNDO = 3
ID_EDIT_REDO = 4
file_menu.Append(ID_FILE_NEW,"New Window","This is a new window")
file_menu.Append(ID_FILE_OPEN,"Open...","This will open a new window")
edit_menu.Append(ID_EDIT_UNDO,"Undo","This will undo your last action")
edit_menu.Append(ID_EDIT_REDO,"Redo","This will redo your last undo")
menubar.Append(file_menu,"File")
menubar.Append(edit_menu,"Edit")
self.SetMenuBar(menubar)
self.Bind(wx.EVT_MENU, self.test, None, 1)
def test(self, event):
self.new = NewWindow(parent=None, id=-1)
self.new.Show()
class NewWindow(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self, parent, id, 'New Window', size=(400,300))
wx.Frame.CenterOnScreen(self)
#self.new.Show(False)
if __name__=='__main__':
app=wx.PySimpleApp()
frame=MainWindow(parent=None,id=-1)
frame.Show()
app.MainLoop()

wxPython - How to force UI refresh?

I've boiled my problem down to the example code shown in this post. Note that I'm not calling app.MainLoop() because this isn't an interactive window; I want it to pop up at the beginning, show some progress bars while work happens, and disappear when complete.
My (limited) understanding of wxPython and wx.Yield() led me to believe that calling wx.Yield() after some UI work would flush those changes to the display. That is not occurring -- when I run this script, there is a gray box where "Hello World" should be.
What am I doing wrong?
import wx
class MyFrame(wx.Frame):
def __init__(self, parent, id):
wx.Frame.__init__(self, parent, id, size=(400,400))
self.panel = wx.Panel(self, -1)
wx.StaticText(self.panel, -1, "Hello World", (20,20))
wx.Yield()
class MyApp(wx.App):
def OnInit(self):
self.frame = MyFrame(None, -1)
self.frame.Show(True)
self.SetTopWindow(self.frame)
return True
def run():
app = MyApp(redirect=False)
import time; time.sleep(5)
run()
You need to be yielding or updating on a regular basis, so that when your OS/window manager sends repaint messages to your app, it can handle them. I am not 100% sure about wxPython as I haven't used it recently but I don't think you can do what you want without the main loop to handle the messages appropriately.
You might find something useful here about threading the main loop, however (as well as explanation of why the main loop is important): http://wiki.wxpython.org/MainLoopAsThread
instead of wx.Yield()
just call self.Update()
Without the MainLoop no events will be fired and also .Refresh will not work.
I guess wxSplashscreen may be what you are looking for. Example: http://wiki.wxpython.org/SplashScreen
Not that it will do the original poster any good after all this time but wx.Yield() would have done the job. It just needs to be in the right place as does the self.Show()
The following outputs a progress bar which gets updated.
import wx
import time
class MyFrame(wx.Frame):
def __init__(self, parent, id):
wx.Frame.__init__(self, parent, id, size=(290,200))
self.panel = wx.Panel(self, -1)
wx.StaticText(self.panel, -1, "Hello World", (20,20))
self.gauge = wx.Gauge(self.panel, -1, 50, pos=(20,50), size=(250, 20))
self.Show()
n = 0
while n < 50:
n = n+1
self.gauge.SetValue(n)
wx.Yield()
time.sleep(1)
class MyApp(wx.App):
def OnInit(self):
self.frame = MyFrame(None, -1)
self.SetTopWindow(self.frame)
return True
def run():
app = MyApp()
run()

Categories