2

I have been looking around the Internet but I am not sure if there is a way to show 2 classes in wxPython in 2 separate windows. And could we communicate between them (like one class being the dialog and the other the main class)?

I think I did this before using Show() but I am not sure how to repeat this.

So basically I would like to be able to have a dialog but by using a class instead. This would be more powerful than using Modal dialogs.

Thanks

2 Answers 2

7

Here you have a simple example of two frames communicating:

enter image description here

The trick is in sending an object reference to share between frames, either creating one inside the other (as in this case) or through a common parent. The code is:

import wx

class MainFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, size=(150,100), title='MainFrame')
        pan =wx.Panel(self)
        self.txt = wx.TextCtrl(pan, -1, pos=(0,0), size=(100,20), style=wx.DEFAULT)
        self.but = wx.Button(pan,-1, pos=(10,30), label='Tell child')
        self.Bind(wx.EVT_BUTTON, self.onbutton, self.but)
        self.child = ChildFrame(self)
        self.child.Show()

    def onbutton(self, evt):
        text = self.txt.GetValue()
        self.child.txt.write('Parent says: %s' %text)


class ChildFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, None, size=(150,100), title='ChildFrame')
        self.parent = parent
        pan = wx.Panel(self)
        self.txt = wx.TextCtrl(pan, -1, pos=(0,0), size=(100,20), style=wx.DEFAULT)
        self.but = wx.Button(pan,-1, pos=(10,30), label='Tell parent')
        self.Bind(wx.EVT_BUTTON, self.onbutton, self.but)

    def onbutton(self, evt):
        text = self.txt.GetValue()
        self.parent.txt.write('Child says: %s' %text)


if __name__ == "__main__":

    App=wx.PySimpleApp()
    MainFrame().Show()
    App.MainLoop()
Sign up to request clarification or add additional context in comments.

Comments

1

You can also use pubsub to communicate between two frames. I show one way of doing just that in this article: http://www.blog.pythonlibrary.org/2010/06/27/wxpython-and-pubsub-a-simple-tutorial/

If you don't want the first frame to hide itself, just remove the line with the Hide() in it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.