wxPython: Inserting an unknown control in XRC to use a custom widget

I’ve been quite busy lately with getting my application done and it has improved by leaps and bounds (I may go into the intricacies of lxml, but I think the tutorials are fairly comprehensive). Most of it was basic stuff that just needed to be pieced together, so there was no real reason to post any code. All of it is documented fairly well in the wxpython wiki and its many, many tutorials (I’m too lazy to mention them this time, just do a google search).

However, recently I came across an issue that annoyed me a little and I finally got round to addressing it. I wanted to have a bitmap button in toggle state (2-state). Unfortunately, wxpython does not allow bitmap buttons to have a toggle state 😦 The answer to this was the use of a PlateButton (Here’s a good introductory tutorial). But since this is a custom widget of the wxpython library, I am not able to use it in XRC, since it is based on wxWidgets.

So what to do? After asking many a lovely person on the interwebs, I finally found a satisfactory but not complete answer. The solution lay with the XmlResource.AttachUnknownControl function (Tutorial).

It allows you to enter a placeholder within the XRC file which can be later filled using the above function. The code I used goes as follows:

First the placeholder was inserted with the following code within the XRC file:

This was followed by the insertion of the following code into my python file:

class MyFrame(wx.Frame):
    def __init__(self, parent):
        self.res = xrc.XmlResource("my_xrc_file.xrc")
        self.frame = self.res.LoadFrame("MyFrame")

        imageFile = "/a/path/to/your/file"
        png = wx.Image(imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap()

        self.MyBtn = wx.lib.platebtn.PlateButton(self.frame, bmp=png,
        self.PlateBtn = self.res.AttachUnknownControl("MyBtn",
                                        self.MyBtn, self.frame)

There really is nothing exciting about the code in this example apart from the fact that you need to know that the possibility exists. Self.PlateBtn returns a bool so you need to bind your functions to self.MyBtn. Very useful to know this.

So far, I have not been able to affect the platebutton after I initialised it, that is a bit of a downside and unfortunately it looks entirely different to the rest of the buttons. I will probably end up changing all of the buttons to platebuttons, just for consistency. As a consequence, the XRC file is a bit useless, but hey, thats life.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s