python logo


Tag: button

wxpython button

To create a button simply call wx.Button(). When creating a button with wx.Button() it is important to parse the panel as first argument. We attach it to a panel because attaching to the frame would make it full screen.

A panel gives you to option to position widgets anywhere in the window. The parameter (10,10) is the position on the panel. The id argument is necessary, but it is equal to -1 (wx.ID_ANY == -1). The 3rd parameter is the text on the button.

Related course:
Creating GUI Applications with wxPython

You can use the code below to create a button in wxPython:

#!/usr/bin/python

import wx

def onButton(event):
print "Button pressed."

app = wx.App()
frame = wx.Frame(None, -1, 'win.py')
frame.SetDimensions(0,0,200,50)

panel = wx.Panel(frame, wx.ID_ANY)
button = wx.Button(panel, wx.ID_ANY, 'Test', (10, 10))
button.Bind(wx.EVT_BUTTON, onButton)

frame.Show()
frame.Centre()
app.MainLoop()

The function onButton() is called if the button is pressed. We bind (connect) it with button.Bind(wx.EVT_BUTTON, onButton).

Output:

wx button Buton created with wxPython

Image on button
wxPython supports having images on buttons. Only a minor change is needed to display an image on a button. While the function is called wx.BitmapButton, it supports other image formats.

bmp = wx.Bitmap("call-start.png", wx.BITMAP_TYPE_ANY)
button = wx.BitmapButton(panel, id=wx.ID_ANY, bitmap=bmp,
size=(bmp.GetWidth()+10, bmp.GetHeight()+10))

The first line loads the image, the second line creates the button.

Full code:

#!/usr/bin/python

import wx

def onButton(event):
print "Button pressed."

app = wx.App()
frame = wx.Frame(None, -1, 'win.py')
frame.SetDimensions(0,0,200,70)
panel = wx.Panel(frame, wx.ID_ANY)

bmp = wx.Bitmap("call-start.png", wx.BITMAP_TYPE_ANY)
button = wx.BitmapButton(panel, id=wx.ID_ANY, bitmap=bmp,
size=(bmp.GetWidth()+10, bmp.GetHeight()+10))

button.Bind(wx.EVT_BUTTON, onButton)
button.SetPosition((10,10))

frame.Show()
frame.Centre()
app.MainLoop()

Output:

wxButton wxButton

Related course:
Creating GUI Applications with wxPython