Adding an image to a button

I have this:

GUI

Here is some code that created the above image:

hbox = wx.BoxSizer(wx.HORIZONTAL)
_img = wx.StaticBitmap()
_img.Create(parent, label=wx.Bitmap(os.path.join(
    os.path.dirname(__file__), 'images', 'exit-to-app.svg')))
hbox.Add(_img, proportion=1, flag=wx.ALIGN_CENTER | wx.ALL)
_exit = wx.Button(parent, label="Exit")
_exit.SetBackgroundColour('#5968c3')
self.Bind(wx.EVT_BUTTON, self.OnQuit, _exit)
hbox.Add(_exit, proportion=1, flag=wx.ALIGN_CENTER | wx.ALL)
return hbox

How to add the bitmap to the button?

Upvotes: 0

Views: 1848

Answers (2)

Rolf of Saxony
Rolf of Saxony

Reputation: 22438

You can use the wx.lib.buttons library, although the buttons may be a bit plain.
However, as @RobinDunn points out, and he should know, Since version 2.9.1 wx.Button supports showing both text and an image (currently only when using wxMSW, wxGTK or OSX/Cocoa ports).

On Linux, I had to ensure that in desktop settings I had set Show Icons on Buttons or the 2nd method using just wx.Button didn't display the image.
Using the second method, the button look much nicer, losing that flat look.

import wx
import wx.lib.buttons as buts
class TestFrame(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)
        pause_button = buts.GenBitmapTextButton(self, -1, bitmap=wx.Bitmap("pause.png"), label= "Pause")
        play_button = buts.GenBitmapTextButton(self, -1, bitmap=wx.Bitmap("play.png"), label= "Play")
        time_button = wx.Button(self, -1, label= "Time")
        time_button.SetBitmap(wx.Bitmap("toggle1.png"),wx.RIGHT)
        box = wx.BoxSizer(wx.HORIZONTAL)
        box.Add(pause_button, 0, wx.CENTER | wx.ALL,10)
        box.Add(play_button, 0, wx.CENTER | wx.ALL,10)
        box.Add(time_button, 0, wx.CENTER | wx.ALL,10)
        self.SetSizerAndFit(box)
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
        pause_button.Bind(wx.EVT_BUTTON, self.OnPause)
        play_button.Bind(wx.EVT_BUTTON, self.OnPlay)
        time_button.Bind(wx.EVT_BUTTON, self.OnTime)
        self.Show()

    def OnCloseWindow(self, event):
        self.Destroy()
    def OnPause(self, event):
        print "Pause pressed"
    def OnPlay(self, event):
        print "Play pressed"
    def OnTime(self, event):
        print "Time pressed"

if __name__ == "__main__":
    app = wx.App()
    frame = TestFrame(None, -1, "wxBitmap Test")
    app.MainLoop()

enter image description here

Upvotes: 1

RobinDunn
RobinDunn

Reputation: 6306

wx.Button has supported adding a bitmap to the label for a while now, although on GTK builds I think it also depends on a global preference whether the icon will be displayed or not, and probably also on the active theme. See the Button sample in the demo for an example.

https://github.com/wxWidgets/Phoenix/blob/master/demo/Button.py#L28

Upvotes: 1

Related Questions