How do I make a button

In part 1, we described several examples of buttons, so we will only briefly cover the basics here. Figure 7.4 displays a simple button.

Using a button is very straightforward. Listing 7.4 displays the code for this simple button example. Figure 7.4 A simple buttĀ°n

Listing 7.4 Creating and displaying a simple button import wx class ButtonFrame(wx.Frame):

wx.Frame._init_(self, None, -1, 'Button Example', size=(3 00, 100)) panel = wx.Panel(self, -1)

self.button = wx.Button(panel, -1, "Hello", pos=(50, 20)) self.Bind(wx.EVT_BUTTON, self.OnClick, self.button) self.button.SetDefault()

def OnClick(self, event):

self.button.SetLabel("Clicked")

if __name__ == '__main__': app = wx.PySimpleApp() frame = ButtonFrame() frame.Show() app.MainLoop()

The wx.Button constructor is similar to constructors we've already seen, as in the following:

wx.Button(parent, id, label, pos, size=wxDefaultSize, style=0, validator, name="button")

The argument specific to wx.Button is the label, the text displayed on the button. It can be changed during the program with SetLabel(), and retrieved with Get-Label(). Two other useful methods are GetDefaultSize(), which returns the system suggested default button size (useful for consistency across frames), and SetDefault(), which sets that button as the default for the dialog or frame. The default button is often drawn differently than other buttons and is typically activated by pressing Enter while the dialog has focus.

The wx.Button class has one cross-platform style flag, wx.BU_EXACTFIT. If defined, the button does not use the system default size as a minimum, but

^ Button Example

instead is sized as small as possible while allowing the label to fit. If the native widget supports it, you can change the alignment of the label within the button using the flags wx.bu_left, wx.bu_right, wx.bu_top, and wx.bu_bottom. Each flag aligns the label to exactly the side you would expect based on its name. As we discussed in part 1, a wx.Button triggers one command event when clicked, with the event type evt_button.

Was this article helpful?

0 0

Post a comment