Tag Archives: wxPython

ANN: The wxPython Cookbook Kickstarter

Several years ago, the readers of this blog asked me to take some of my articles and turn them into a cookbook on wxPython. I have finally decided to do just that. I am including over 50 recipes that I am currently editing to make them more consistent and updating them to be compatible with the latest versions of wxPython. I currently have nearly 300 pages of content!

To help fund the initial production of the book, I am doing a fun little Kickstarter campaign for the project. The money raised will be used for the unique perks offered in the campaign as well as various production costs related to the book, such as ISBN acquisition, artwork, software expenses, advertising, etc.

In case you don’t know what wxPython is, the wxPython package is a popular toolkit for creating cross platform desktop user interfaces. It works on Windows, Mac and Linux with little to no modification of your code base.

The examples in my book will work with both wxPython 3.0.2 Classic as well as wxPython Phoenix, which is the bleeding edge of wxPython that supports Python 3. If I discover any recipes that do not work with Phoenix, they will be clearly marked or there will be an alternative example given that does work.

Here is a listing of the current set of recipes in no particular order:

  • Adding / Removing Widgets Dynamically
  • How to put a background image on a panel
  • Binding Multiple Widgets to the Same Handler
  • Catching Exceptions from Anywhere
  • wxPython’s Context Managers
  • Converting wx.DateTime to Python datetime
  • Creating an About Box
  • How to Create a Login Dialog
  • How to Create a “Dark Mode”
  • Generating a Dialog from a Config File
  • How to Disable a Wizard’s Next Button
  • How to Use Drag and Drop
  • How to Drag and Drop a File From Your App to the OS
  • How to Edit Your GUI Interactively Using reload()
  • How to Embed an Image in the Title Bar
  • Extracting XML from the RichTextCtrl
  • How to Fade-in a Frame / Dialog
  • How to Fire Multiple Event Handlers
  • Making your Frame Maximize or Full Screen
  • Using wx.Frame Styles
  • Get the Event Name Instead of an Integer
  • How to Get Children Widgets from a Sizer
  • How to Use the Clipboard
  • Catching Key and Char Events
  • Learning How Focus Works in wxPython
  • Making Your Text Flash
  • Minimizing to System Tray
  • Using ObjectListView instead of ListCtrl
  • Making a Panel Self-Destruct
  • How to Switch Between Panels
  • wxPython: Using PyDispatcher instead of Pubsub
  • Creating Graphs with PyPlot
  • Redirect Python’s Logging Module to a TextCtrl
  • Redirecting stdout / stderr
  • Resetting the Background Color
  • Saving Data to a Config File
  • How to Take a Screenshot of Your wxPython App and Print it
  • Creating a Simple Notebook
  • Ensuring Only One Instance Per Frame
  • Storing Objects in ComboBox or ListBox Widgets
  • Syncing Scrolling Between Two Grids
  • Creating Taskbar Icons
  • A wx.Timer Tutorial
  • How to Update a Progress Bar from a Thread
  • Updating Your Application with Esky
  • Creating a URL Shortener
  • Using Threads in wxPython
  • How to Create a Grid in XRC
  • An Introduction to XRC

 Note: Recipe names and order are subject to change

wxpython_cookbook_final

Python 101: Redirecting stdout

Redirecting stdout to something most developers will need to do at some point or other. It can be useful to redirect stdout to a file or to a file-like object. I have also redirected stdout to a text control in some of my desktop GUI projects. In this article we will look at the following:

  • Redirecting stdout to a file (simple)
  • The Shell redirection method
  • Redirecting stdout using a custom context manager
  • Python 3’s contextlib.redirect_stdout()
  • Redirect stdout to a wxPython text control

Continue reading Python 101: Redirecting stdout

wxPython’s Context Managers

The wxPython toolkit added context managers to its code base a few years ago, but for some reason you don’t see very many examples of their use. In this article, we’ll look at three examples of context managers in wxPython. A wxPython user was the first person to suggest using context managers in wxPython on the wxPython mailing list. We’ll start off by rolling our own context manager and then look at a couple of examples of built-in context managers in wxPython.

Continue reading wxPython’s Context Managers

wxPython: Ensuring Only One Instance Per Frame

The other day, I came across an interesting StackOverflow question where the fellow was trying to figure out how to open a sub-frame only once. Basically he wanted a single instance of the sub-frame (and other sub-frames). After digging around a bit on Google, I found an old thread from the wxPython Google Group that had an interesting approach to doing what was needed.

Basically it required a bit of meta-programming, but it was a fun little exercise that I thought my readers would find interesting. Here’s the code:

Continue reading wxPython: Ensuring Only One Instance Per Frame

wxPython: Extracting XML from the RichTextCtrl

I recently came across a StackOverflow question where the fellow was asking how to get wxPython’s RichTextCtrl’s XML data so he could save it to a database. I don’t know much about this control, but after a quick Google search, I found an article from 2008 that gave me the information I needed. I took that example and cut it down to the following example:

Continue reading wxPython: Extracting XML from the RichTextCtrl

wxPython 101: Simple Frames

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:

Continue reading wxPython 101: Simple Frames

wxPython 101: How to Center a Widget

I see this come up from time to time where people will ask how to center a widget in a window. The solution is actually quite easy. In most cases, you just need to nest a Horizontal BoxSizer inside of a Verticel BoxSizer with some spacers. In this article, I’ll show you two three different ways to accomplish this task.

wx_centered

Continue reading wxPython 101: How to Center a Widget

wxPython: Freeze and Thaw

The wxPython library comes with a pair of handy methods called Freeze() and Thaw(). The call to Freeze() prevents the window from updating while it is frozen. This can be useful when you are adding or removing widgets and you want to reduce your UI from appearing to flicker. After you finish updating the UI, then you call the Thaw() method so that the user will be able to see the update.

Let’s take a look at a simple example.

Continue reading wxPython: Freeze and Thaw

wxPython: Converting wx.DateTime to Python datetime

The wxPython GUI toolkit includes its own date / time capabilities. Most of the time, you can just use Python’s datetime and time modules and you’ll be fine. But occasionally you’ll find yourself needing to convert from wxPython’s wx.DateTime objects to Python’s datetime objects. You may encounter this when you use the wx.DatePickerCtrl widget.

Fortunately, wxPython’s calendar module has some helper functions that can help you convert datetime objects back and forth between wxPython and Python. Let’s take a look:

def _pydate2wxdate(date):
     import datetime
     assert isinstance(date, (datetime.datetime, datetime.date))
     tt = date.timetuple()
     dmy = (tt[2], tt[1]-1, tt[0])
     return wx.DateTimeFromDMY(*dmy)
 
def _wxdate2pydate(date):
     import datetime
     assert isinstance(date, wx.DateTime)
     if date.IsValid():
          ymd = map(int, date.FormatISODate().split('-'))
          return datetime.date(*ymd)
     else:
          return None

You can use these handy functions in your own code to help with your conversions. I would probably put these into a controller or utilities script. I would also rewrite it slightly so I wouldn’t import Python’s datetime module inside the functions. Here’s an example:

import datetime
import wx
 
def pydate2wxdate(date):
     assert isinstance(date, (datetime.datetime, datetime.date))
     tt = date.timetuple()
     dmy = (tt[2], tt[1]-1, tt[0])
     return wx.DateTimeFromDMY(*dmy)
 
def wxdate2pydate(date):
     assert isinstance(date, wx.DateTime)
     if date.IsValid():
          ymd = map(int, date.FormatISODate().split('-'))
          return datetime.date(*ymd)
     else:
          return None

You can read more about this topic on this old wxPython mailing thread. Have fun and happy coding!

wxPython: How to Create a Login Dialog

I’ve been using wxPython for quite a while now and I see certain questions come up on a fairly frequent basis. One of the popular ones is how to ask the user for their credentials before loading up the rest of the application. There are several approaches to this, but I am going to focus on a simple solution as I believe this solution can be used as the basis for more complex solutions.

Basically what we want to happen is for the user to see a login dialog where they have to enter their username and password. If they enter it correctly, then the program will continue to load and they’ll see the main interface. You see this a lot on websites with a common use case being web email clients. Desktop applications don’t include this functionality as often, although you will see it for Stamps.com’s application and for law enforcement software. We will be creating a dialog that looks like this:

wxLogin.png Continue reading wxPython: How to Create a Login Dialog