How do I make a button with a bitmap

Occasionally, you'll want a picture on your button, rather than a text label, as in figure 7.5.

In wxPython, use the class wx.BitmapButton to create a button with a picture. The code to manage a wx.BitmapButton is very similar to the general button code, as displayed in listing 7.5.

Listing 7.5 Creating a bitmap button import wx class BitmapButtonFrame(wx.Frame):

wx.Frame._init_(self, None, -1, 'Bitmap Button Example', size=(2 00, 150)) panel = wx.Panel(self, -1)

bmp = wx.Image("bitmap.bmp", wx.BITMAP_TYPE_BMP).ConvertToBitmap() self.button = wx.BitmapButton(panel, -1, bmp, pos=(10, 20)) self.Bind(wx.EVT_BUTTON, self.OnClick, self.button) self.button.SetDefault()

self.button2 = wx.BitmapButton(panel, -1, bmp, pos=(100, 20), style=0)

self.Bind(ex.EVT_BUTTON, self.OnClick, self.button2)

def OnClick(self, event): self.Destroy()

app = wx.PySimpleApp() frame = BitmapButtonFrame() frame.Show() app.MainLoop()

The primary difference is that for a bitmap button you need to supply a bitmap, rather than a label. Otherwise, the constructor and most of the code is

Figure 7.5 A demonstration of a basic bitmap button. The left button is drawn with a 3D effect.

Figure 7.5 A demonstration of a basic bitmap button. The left button is drawn with a 3D effect.

identical to the text button case. A bitmap button emits the same EVT_BUTTON event when clicked.

There are a couple of interesting features related to bitmap buttons. First, there's a style flag, wx.bu_autodraw, which is on by default. If the flag is on, the bitmap is surrounded by a 3D border to make it look like a text button (left button of figure 7.5), and the button is a few pixels larger than the original bitmap. If the flag is off, the bitmap is simply drawn as a button with no border. The right button in figure 7.5 shuts off the default by setting style=0, and it does not have the 3D effect.

By default, simply pass wxPython a single bitmap for the main display, and wxPython automatically creates standard derivative bitmaps when the button is pressed, has the focus, or is disabled. If the normal behavior is not what you want, you can explicitly tell wxPython which bitmaps to use with the following methods: SetBitmapDisabled(), SetBitmapFocus(), SetBitmapLabel(), and SetBitmap-Selected(). Each of these methods takes a wx.Bitmap object, and each has an associated getter function.

You cannot combine a bitmap and text by using the normal wxWidgets C + + library. You could create a bitmap that contains text. However, as we'll see in the generic button question, there is a wxPython addition that allows this behavior.

Was this article helpful?

0 0

Post a comment