Category Archives: GUI Toolkits

wxPython Cookbook Cover Story

I always spend some time thinking about how I want my book’s cover to look. When I was designing the Cookbook’s cover, I thought mostly about food and chefs. I had originally thought I might have some kind of kitchen scene with mice in chef hats and a snake on the mantle. But I wanted to take the idea of cooking and put a twist on it.

Instead of a kitchen, I thought of cowboys herding cattle and how they usually had a cook with them. So I went with that idea, although I didn’t have the herds of animals added to the cover.

To help differentiate the Cookbook from my previous works, I hired a different artist from my previous titles named Liza Tretyakova. You can check out some of her work on Behance or even contact her directly by email (schimmel@inbox.ru) if you happen to need a great artist.

I thought it might be fun for you to see how the cover art evolved as I worked with the artist to get my ideas for the cover turned into reality. Let’s start with the first sketch I got from Liza:

wxpython_cookbook_cover_sketch

Continue reading wxPython Cookbook Cover Story

wxPython Cookbook Sample Chapters

My newest book will be my own home brewed version of a wxPython Cookbook. If you’re interested in learning more about it, then please check out the Kickstarter campaign. The brief synopsis is that it will have a little over 50 recipes in the book and around 300 pages of content.

To help you make an informed decision about whether or not you would like to support the book, I am releasing a few sample chapters. You can download them here as a PDF. Please note that these chapters are in a beta state. I will be updating the vast majority of the book with new screenshots and updated code examples where appropriate as well as various other tweaks and enhancements.

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

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

An Intro to EasyGUI_Qt

I recently came across a fun little project called EasyGUI_Qt. It’s basically the same thing as EasyGUI except that it uses PyQt4 instead of Tkinter. The idea behind both of these packages is to allow the developer to ask the user simple questions using dialogs.

In this article, we’ll spend some time learning how to use this package by looking at a few examples. Note that EasyGUI_Qt works with both Python 2 and 3, although its primary target is Python 3. The documentation states that there may be some issues with unicode in Python 2, but other than that, the widgets should work fine.

Continue reading An Intro to EasyGUI_Qt

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!

Tkinter – Redirecting stdout / stderr

Redirecting stdout seems to be a pretty common request on the wxPython users group, so I decided to see how easy it would be to do it with Tkinter. The typical use case for redirecting stdout or stderr is that you are calling some other process (like ping or tracert) and you want to catch what it’s doing to put it into your UI. Usually you can just use Python’s subprocess module and call its communicate() method to access the data. Then you can just print it to stdout and it will magically appear in your UI’s widget of choice.

Our finished user interface will look something like the following:

tkredirect.png

Let’s find out how to do this with Tkinter: Continue reading Tkinter – Redirecting stdout / stderr