I wrote a little about this, but I was using SQLAlchemy. This was my first attempt:
Then I received some comments and help from friend in the wxPython community and SQLAlchemy's devs and updated the app a bit:
This second article shows how to create a database session and pass it about. I think that's the approach you are looking for. I would do the database connection in your top level frame's init method:
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, None, title="Databases!")
self.data_connection = self.create_connection()
Then when you create your other frames, you can pass that connection to them:
def create_new_frame(self):
""""""
new_frame = MyOtherFrame(self.data_connection)
new_frame.Show()
Here's one way you could set up your frame class:
########################################################################
class MyOtherFrame(wx.Frame):
""""""
#----------------------------------------------------------------------
def __init__(self, data_connection):
"""Constructor"""
wx.Frame.__init__(self, None, title="Other frame")
self.data_connection = data_connection
Just make sure you do not close the data connection in your other frame as that will also close it in the original top level frame.
This solution also applies to your OnButton1 call. Just change it so it's like this:
def OnButton1(self, event):
cursor = self.data_connection.cursor()
You'll notice that you can access self.data_connection anywhere in your main frame because it was defined as a class level variable.
You might also be interested in the Dabo project, which is a wrapper around wxPython that is supposed to make it easier to work with databases: http://www.dabodev.com/