In this tutorial, we'll look at three simple ways to create a wxPython frame. If you're a visual learner, I also created a screencast version of this article that you can view below:
I call the following a "stupid" example because it's not very useful. You can't extend this example very easily, but I use it as an example because you can still find wxPython snippets like this. They do work, but they're not recommended.
import wx app = wx.App(False) frame = wx.Frame(None, title='test') frame.Show() app.MainLoop()
Let's look at a more realistic example!
In this example, we subclass wx.Frame and add a wx.Panel object. The Panel adds correct tabbing between widgets and the correct look and feel. For example, if you don't have a panel on Windows, your frame will look kind of strange.
import wx ######################################################################## class MyFrame(wx.Frame): """""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" wx.Frame.__init__(self, None, title='Test') panel = wx.Panel(self) btn = wx.Button(panel, label='Press Me') self.Show() if __name__ == '__main__': app = wx.App(False) frame = MyFrame() app.MainLoop()
You will notice that in this example, I also added a button widget. This is just to show you how much easier it is to add additional widgets to your frame. Now we'll move on and separate out the panel into its own class.
For this example, we will separate our the panel into its own class. Let's take a look!
import wx ######################################################################## class MyPanel(wx.Panel): """""" #---------------------------------------------------------------------- def __init__(self, parent): """Constructor""" wx.Panel.__init__(self, parent) btn = wx.Button(self, label='Press Me') ######################################################################## class MyFrame(wx.Frame): """""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" wx.Frame.__init__(self, None, title='Test') panel = MyPanel(self) self.Show() if __name__ == '__main__': app = wx.App(False) frame = MyFrame() app.MainLoop()
The reason I like doing this is that it helps reduce the number of lines of code per class. It also makes it easy to move the panel class into its own module if it gets to be too large. Then I can just import the panel! There is a trade-off, of course, in that now you'll have to find a way to communicate between the two classes. This is typically easy to do and I usually use pubsub for that purpose, but I have seen other approaches mentioned on the wxPython mailing list.
Now you know how to create your own frames in wxPython. There are lots of different approaches to creating widgets and managing your code. I hope you found these examples helpful in figuring out how to layout your own code.
Copyright © 2024 Mouse Vs Python | Powered by Pythonlibrary