In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Today, I will talk to you about how to use the basic control buttons of wxpython in Python. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.
Working with buttons there are many different types of buttons in wxPython. In this section, we will discuss text buttons, bitmap buttons, switch buttons (toggle buttons), and generic buttons.
How do I generate a button? In the first part (part 1), we have shown several examples of buttons, so here we will only briefly cover the basics of it. Figure 7.4 shows a simple button.
Figure 7.4
It is very easy to use buttons. Example 7.4 shows the code for this simple button.
Python code
Import wx
Class ButtonFrame (wx.Frame):
Def _ init__ (self):
Wx.Frame.__init__ (self, None,-1, 'Button Example'
Size= (300,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 constructor for wx.Button is similar to what we have already seen, as follows:
Wx.Button (parent, id, label, pos, size = wxDefaultSize, style = 0, validator, name = "button")
The parameter label is the text displayed on the button. It can be changed using SetLabel () while the program is running and obtained using GetLabel (). Two other useful methods are GetDefaultSize () and SetDefault (). GetDefaultSize () returns the size of the system default button (useful for consistency between frames); the SetDefault () setting button is the default button for the dialog box or frame. The default button is drawn differently from other buttons and is usually activated by pressing enter when the dialog box gets focus.
The wx.Button class has a cross-platform style tag: wx.BU_EXACTFIT. If this tag is defined, the button does not take the default size of the system as the minimum size, but the size that happens to fill the label as the minimum size. If the local widget supports it, you can use the tags wx.BU_LEFT, wx.BU_RIGHT, wx.BU_TOP, and wx.BU_BOTTOM to change the alignment of the tags in the button. Each tag aligns the label to the edge, which you can know according to the name of the tag. As we discussed in the first part, wx.Button triggers a command event when it is hit, and the event type is EVT_BUTTON.
How do I generate a bitmap button? Sometimes, you may want to display an image on your button instead of a text label, as shown in figure 7.5.
In wxPython, use the class wx.BitmapButton to create a bitmap button. The code that handles a wx.BitmapButton is very similar to the code for a general-purpose button, and example 7.5 shows the code that produces 7.5.
Example 7.5 create a bitmap button
Python code
Import wx
Class BitmapButtonFrame (wx.Frame):
Def _ init__ (self):
Wx.Frame.__init__ (self, None,-1, 'Bitmap Button Example'
Size= (200,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 (wx.EVT_BUTTON, self.OnClick, self.button2)
Def OnClick (self, event):
Self.Destroy ()
If _ _ name__ = ='_ _ main__':
App = wx.PySimpleApp ()
Frame = BitmapButtonFrame ()
Frame.Show ()
App.MainLoop ()
The main difference from a normal button is that you need to provide a bitmap, not a label. Otherwise, the constructor and most of the code is the same as the example of a text button. The bitmap button also generates an EVT_BUTTON event when it is clicked.
There are several interesting features about bitmap buttons. First, a style tag wx.BU_AUTODRAW, which is the default. If the tag is turned on, the bitmap will have a 3D border, which makes it look like a text button (the left button in figure 7.5), and the button is a few pixels larger than the original image. If the tag is off, the bitmap is simply drawn as a button without a border. By setting style = 0 so that the button on the right in figure 7.5 turns off the default settings, it has no 3D effect.
By default, a single bitmap is passed to wxPython as the main display bitmap, and when the button is pressed or gained focus or invalid, wxPython automatically creates a standard derived bitmap for autonomous display as the bitmap displayed on the button at this time. If the automatically created bitmap is not what you want, you can use the following methods: SetBitmapDisabled (), SetBitmapFocus (), SetBitmapLabel (), and SetBitmap-Selected () explicitly tell wxPython which bitmap you want to use. Each of these methods requires a wx.Bitmap object as a parameter, and they all have corresponding get* () methods.
You can't merge a bitmap with text by using the standard wxWidgets C++ library. You can create a bitmap that contains text. However, as we will see in the discussion of generic buttons, wxPython has additional ways to implement this merge behavior.
= how do I create a switch button (toggle button)? =
You can use wx.ToggleButton to create a switch button (toggle button). The switch button (toggle button) looks a lot like a text button, but it behaves more like a check box, and its selected or non-selected state is visual. In other words, when you press a switch button (togglebutton), it will remain pressed until you hit it again.
There is only three differences between wx.ToggleButton and parent wx.Button:
1. When tapped, wx.ToggleButton sends an EVT_TOGGLEBUTTON event.
2. Wx.ToggleButton has GetValue () and SetValue () methods, which deal with the binary state of the button.
The switch button (toggle button) is useful and is another good choice relative to the check box, especially in the toolbar. Remember, you can't use the objects provided by wxWidgets to merge switch buttons (toggle button) with bitmap buttons, but wxPython has a generic button class that provides this behavior, which we'll discuss in the next section.
What is a universal button and why should I use it? The Universal Button is a button widget reimplemented entirely in Python, avoiding the use of native system widgets. Its parent class is wx.lib.buttons. GenButton . Universal buttons have universal bitmaps and toggle buttons.
Here are several reasons for using universal buttons:
1. General buttons have a better cross-platform appearance than local buttons. On the other hand, generic buttons may look slightly different from local buttons on a specific system.
2. With a generic button, you have more control over its appearance and can change properties, such as the width and color of the 3D bevel, which may not be allowed for local controls.
3. The general button class allows the merging of features, but not the wxWidget button. For example, GenBitmapTextButton allows the combination of text labels and bitmaps, and GenBitmapToggleButton implements a bitmap toggle button.
4. If you are creating a button class, it is easier to use generic buttons. Because its code and parameters are written in Python, they are more useful for checking and overriding when creating a new subclass.
Figure 7.6 shows a comparison between the actual generic button and the regular button.
Figure 7.6
Example 7.6 shows the code that produces figure 7.6. The second import statement, import wx.lib.buttons as buttons, is required, which makes the generic button class available.
Example 7.6 create and use a generic button for wxPython
Python code
Import wx
Import wx.lib.buttons as buttons
Class GenericButtonFrame (wx.Frame):
Def _ init__ (self):
Wx.Frame.__init__ (self, None,-1, 'Generic Button Example'
Size= (500,350))
Panel = wx.Panel (self,-1)
Sizer = wx.FlexGridSizer (1,3,20,20)
B = wx.Button (panel,-1, "A wx.Button")
B.SetDefault ()
Sizer.Add (b)
B = wx.Button (panel,-1, "non-default wx.Button")
Sizer.Add (b)
Sizer.Add ((100.10))
B = buttons.GenButton (panel,-1, 'Genric Button') # basic universal button
Sizer.Add (b)
B = buttons.GenButton (panel,-1, 'disabled Generic') # invalid generic button
B.Enable (False)
Sizer.Add (b)
B = buttons.GenButton (panel,-1, 'bigger') # Custom size and color buttons
B.SetFont (wx.Font (20, wx.SWISS, wx.NORMAL, wx.BOLD, False))
B.SetBezelWidth (5)
B.SetBackgroundColour ("Navy")
B.SetForegroundColour ("white")
B.SetToolTipString ("This is a BIG button...")
Sizer.Add (b)
Bmp = wx.Image ("bitmap.bmp", wx.BITMAP_TYPE_BMP) .ConvertToBitmap ()
B = buttons.GenBitmapButton (panel,-1, bmp) # Universal bitmap button
Sizer.Add (b)
B = buttons.GenBitmapToggleButton (panel,-1, bmp) # Universal bitmap switch button
Sizer.Add (b)
B = buttons.GenBitmapTextButton (panel,-1, bmp, "Bitmapped Text"
Size= (175,75) # Bitmap text button
B.SetUseFocusIndicator (False)
Sizer.Add (b)
B = buttons.GenToggleButton (panel,-1, "ToggleButton") # Universal switch button
Sizer.Add (b)
Panel.SetSizer (sizer)
If _ _ name__ = ='_ _ main__':
App = wx.PySimpleApp ()
Frame = GenericButtonFrame ()
Frame.Show ()
App.MainLoop ()
In example 7.6, the use of general buttons is very similar to regular buttons. Generic buttons generate the same EVT_BUTTON and EVT_TOGGLEBUTTON events as regular buttons. The generic button introduces the GetBevelWidth () and SetBevelWidth () methods to change the 3D bevel effect. They are used on the big buttons in figure 7.6.
The generic bitmap button class GenBitmapButton works like the standard wxPython version. In the constructor. GenBitmapTextButton requires a bitmap, followed by text. The generic classes GenToggleButton, GenBitmapToggleButton, and GenBitmapTextToggleButton are the same as the non-switch version, and respond to GetToggle () and SetToggle () for the switch state of the processing button.
In the next section, we will discuss options for enabling your users to enter or view a numeric value.
Enter and display numbers sometimes you want to display graphical digital information, or you want the user to enter a number without having to use the keyboard. In this section, we will browse the tools in wxPython for digital input and display: slider, fine-tuning control boxes, and rulers that display metrics.
How do I generate a slider? The slider is a widget that allows the user to select a numeric value by dragging the indicator within the scale of the control. In wxPython, the control class is wx.Slider, which includes the display of read-only text of the current value of the slider. Figure 7.7 shows an example of horizontal and vertical sliders.
Figure 7.7
The basic use of the slider is very simple, but you can add a lot of events.
How to use the slider
Example 7.7 is an example of producing figure 7.7.
Example 7.7 display code for horizontal and vertical sliders
Python code
Import wx
Class SliderFrame (wx.Frame):
Def _ init__ (self):
Wx.Frame.__init__ (self, None,-1, 'Slider Example'
Size= (300,350))
Panel = wx.Panel (self,-1)
Self.count = 0
Slider = wx.Slider (panel, 100,25,1,100, pos= (10,10)
Size= (250,- 1)
Style=wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_LABELS)
Slider.SetTickFreq (5,1)
Slider = wx.Slider (panel, 100,25,1,100, pos= (125,70)
Size= (- 1,250)
Style=wx.SL_VERTICAL | wx.SL_AUTOTICKS | wx.SL_LABELS)
Slider.SetTickFreq (20,1)
If _ _ name__ = ='_ _ main__':
App = wx.PySimpleApp ()
Frame = SliderFrame ()
Frame.Show ()
App.MainLoop ()
Usually, when you use the wx.Slider class, all you need is a constructor, which is different from other calls, as follows:
Wx.Slider (parent, id, value, minValue, maxValue, pos = wxDefaultPosition, size = wx.DefaultSize, style=wx.SL_HORIZONTAL, validator = wx.DefaultValidator, name = "slider")
Value is the initial value of the slider, while minValue and maxValue are the values at both ends.
Work with slider styl
The style of the slider manages the position and orientation of the slider, as shown in Table 7.9 below.
Table 7.9 wx.Slider style
Wx.SL_AUTOTICKS: if you set this style, the slider will display the scale. The interval between ticks is controlled by the SetTickFreq method.
Wx.SL_HORIZONTAL: horizontal slider. This is the default value.
Wx.SL_LABELS: if you set this style, the slider will display the values at both ends and the current read-only value of the slider. Some platforms may not display the current value.
Wx.SL_LEFT: for vertical sliders, the scale is on the left side of the slider.
Wx.SL_RIGHT: for vertical sliders, the scale is on the right side of the slider.
Wx.SL_TOP: for the horizontal slider, the scale is located at the top of the slider.
Wx.SL_VERTICAL: vertical slider.
If you want to affect the rest of your application by changing the values in the slider, here are a few events that you can use. These events are the same as those emitted by the window scroll bar, which is described in the scroll bar section of Chapter 8.
Table 7.10 lists the Set * () methods you can use with the slider. Each Set * () method has a corresponding Get method-- the description of the Get method refers to its corresponding Set * () method.
Table 7.10
GetRange () SetRange (minValue, maxValue): sets the values at both ends of the slider.
GetTickFreq () SetTickFreq (n, pos): sets the interval of ticks with the parameter n. The parameter pos is not used, but it is still necessary. Set it to 1.
GetLineSize () SetLineSize (lineSize): sets the value that the slider increases or decreases each time you press the steering key.
GetPageSize () SetPageSize (pageSize): sets the value that the slider increases or decreases each time you press the PgUp or PgDn key.
GetValue () SetValue (value): sets the value of the slider.
Although sliders provide a quick and visual representation of values within a possible range, they also have two disadvantages. One is that they take up a lot of space, and the other is that it is difficult to set the slider precisely with the mouse. The fine-tuning controller we will discuss below solves both of the above problems.
How to get those smart up and down arrow buttons? A fine-tuning controller is a combination of a text control and a pair of arrow buttons that adjust numeric values and are the best alternative to the slider when you ask for a minimum screen space. Figure 7.8 shows the fine tuning controller control for wxPython.
Figure 7.8
In wxPython, the class wx.SpinCtrl manages the fine-tuning button and the corresponding text display. In the next section, we will create a fine-tuning controller.
How to create a fine-tuning controller
To change the value using wx.SpinCtrl, press the arrow button or enter it in the text control. Non-numeric text typed is ignored, although the control displays non-numeric text typed. An out-of-range value will be considered as the corresponding maximum or minimum value, although the value you entered is displayed. Example 7.8 shows the use of wx.SpinCtrl.
Example 7.8 using wx.SpinCtrl
Python code
Import wx
Class SpinnerFrame (wx.Frame):
Def _ init__ (self):
Wx.Frame.__init__ (self, None,-1, 'Spinner Example'
Size= (100,100)
Panel = wx.Panel (self,-1)
Sc = wx.SpinCtrl (panel,-1, ", (30, 20), (80,-1))
Sc.SetRange (1100)
Sc.SetValue (5)
If _ _ name__ = ='_ _ main__':
App = wx.PySimpleApp ()
SpinnerFrame () .Show ()
App.MainLoop ()
Almost all the complexity of the fine-tuning control is in its constructor, which is as follows:
Python code
Wx.SpinCtrl (parent, id=-1, value=wx.EmptyString, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.SP_ARROW_KEYS, min=0, max=100, initial=0, name= "wxSpinCtrl")
The parameter value is dummy. Use the initial parameter to set the value of the control, and use min and max to set the range of the control.
There are two style tags for wx.SpinCtrl. The default style is wx.SP_ARROW_KEYS, which allows the user to change the value of the control through the up and down arrow keys on the keyboard. The style wx.SP_WRAP allows the values in the control to change cyclically, that is, when you change the value in the control to the maximum or minimum through the arrow buttons, if you continue, the value will become minimum or maximum, from one extreme to the other.
You can also capture the EVT_SPINCTRL event, which occurs when the value of the control changes (even if the change is caused directly by text input). If the text changes, an EVT_TEXT event is raised, just like if you use a separate text control.
As shown in example 7.8, you can use the SetRange (minVal, maxVal) and SetValue (value) methods to set ranges and values. The SetValue () function requires a string or an integer. To get the value, use the methods: GetValue () (which returns an integer), GetMin (), and GetMax ().
When you need more control over the behavior of the fine-tuning controller, such as allowing floating-point numbers or a list of strings, you can put a wx.SpinButton and a wx.TextCtrl together and make a connection between them. Then capture the event from wx.SpinButton and update the value in wx.TextCtrl.
How do I generate a progress bar? If you only want to graphically display a numeric value without allowing the user to change it, use the corresponding wxPython widget wx.Gauge. The relevant example is the progress bar shown in figure 7.9.
Figure 7.9
Example 7.9 shows the code that produces figure 7.9. Unlike many other examples in this chapter, we have added an event handler here. The following code adjusts the value of the ruler when it is empty so that the value changes over and over again.
Example 7.9 shows and updates a wx.Gauge
Python code
Import wx
Class GaugeFrame (wx.Frame):
Def _ init__ (self):
Wx.Frame.__init__ (self, None,-1, 'Gauge Example'
Size= (350150)
Panel = wx.Panel (self,-1)
Self.count = 0
Self.gauge = wx.Gauge (panel,-1,50, (20,50), (250,25))
Self.gauge.SetBezelFace (3)
Self.gauge.SetShadowWidth (3)
Self.Bind (wx.EVT_IDLE, self.OnIdle)
Def OnIdle (self, event):
Self.count = self.count + 1
If self.count = = 50:
Self.count = 0
Self.gauge.SetValue (self.count)
If _ _ name__ = ='_ _ main__':
App = wx.PySimpleApp ()
GaugeFrame () .Show ()
App.MainLoop ()
The constructor of wx.Gauge is similar to other numeric widgets:
Python code
Wx.Gauge (parent, id, range, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.GA_HORIZONTAL, validator=wx.DefaultValidator, name= "gauge")
When you use the parameter range to specify a numeric value, the value represents the upper limit of the ruler, while the lower limit is always 0. The default style wx.GA_HORIZONTAL provides a horizontal bar. To rotate it 90 degrees, use the wx.GA_VERTICAL style. If you are on Windows, then style wx.GA_PROGRESSBAR gives you a localized progress bar from the Windows toolkit.
As a read-only control, wx.Gauge has no events. However, you can set its properties. You can use GetValue (), Set-Value (pos), GetRange (), and SetRange (range) to adjust its value and range. If you are on Windows and do not use the local progress bar style, you can use SetBezelFace (width) and SetShadowWidth () to change the width of the 3D effect.
Giving users a choice almost every application requires the user to choose between a set of predefined options. In wxPython, there are a variety of widgets to help users with this task, including check boxes, radio buttons, list boxes, and combo boxes. These widgets are described in the following sections.
How do I create a check box? The check box is a switch button with a text label. Check boxes are usually displayed in groups, but the switch status of each check box is independent of each other. You can use the check box when you have one or more options that require explicit switch status. Figure 7.10 shows a set of check boxes.
Figure 7.10
Check boxes are easy to use in wxPython. They are instances of the wx.CheckBox class and can be displayed together by putting them together in a parent container. Example 7.10 provides the code to generate figure 7.10.
Example 7.10 insert three check boxes into a frame
Python code
Import wx
Class CheckBoxFrame (wx.Frame):
Def _ init__ (self):
Wx.Frame.__init__ (self, None,-1, 'Checkbox Example'
Size= (150,200)
Panel = wx.Panel (self,-1)
Wx.CheckBox (panel,-1, "Alpha", (35,40), (150,20))
Wx.CheckBox (panel,-1, "Beta", (35,60), (150,20))
Wx.CheckBox (panel,-1, "Gamma", (35,80), (150,20))
If _ _ name__ = ='_ _ main__':
App = wx.PySimpleApp ()
CheckBoxFrame () .Show ()
App.MainLoop ()
Wx.CheckBox has a typical wxPython constructor:
Python code
Wx.CheckBox (parent, id, label, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, name= "checkBox")
The label parameter is the label text of the check box. Check boxes do not have style tags, but they produce their own unique command event: EVT_CHECKBOX. The switch state of wx.CheckBox can be accessed using the GetValue () and SetValue (state) methods, and its value is a Boolean value. The IsChecked () method is equivalent to the GetValue () method, just to make the code look easier to understand.
How do I create a set of radio buttons (radio button)? A radio button is a widget that allows the user to select one of several options. Unlike check boxes, radio buttons are explicitly configured in groups, and only one of the options can be selected. When a new option is selected, the last selection is turned off. The use of a radio button is more complex than a check box because it needs to be organized into a group for use. Radio button gets its name from the group of select buttons on older cars that behave the same way.
In wxPython, there are two ways to create a set of radio buttons. One is wx.RadioButton, which requires you to create one button at a time, while wx.RadioBox allows you to configure a complete set of buttons with a single object, which are displayed in a rectangle.
The wx.RadioButton class is simpler and is preferred if the radio button has a direct impact on other widgets or if the radio button is not arranged in a single rectangle. Figure 7.11 shows the column children of a set of wx.RadioButton objects.
Figure 7.11
The reason we use wx.RadioButton in this example is that each radio button controls an associated text control. Because the widget is outside this set of radio buttons, we can't just use a single radio button box.
How to create a radio button
Example 7.11 shows the code in figure 7.11, which manages the connection between radio buttons and text controls.
Example 7.11 uses wx.RadioButton to control another widget
Python code
Import wx
Class RadioButtonFrame (wx.Frame):
Def _ init__ (self):
Wx.Frame.__init__ (self, None,-1, 'Radio Example'
Size= (200,200)
Panel = wx.Panel (self,-1)
# create radio button
Radio1 = wx.RadioButton (panel,-1, "Elmo", pos= (20,50), style=wx.RB_GROUP)
Radio2 = wx.RadioButton (panel,-1, "Ernie", pos= (20,80))
Radio3 = wx.RadioButton (panel,-1, "Bert", pos= (20,110))
# create a text control
Text1 = wx.TextCtrl (panel,-1, ", pos= (80,50))
Text2 = wx.TextCtrl (panel,-1, ", pos= (80,80))
Text3 = wx.TextCtrl (panel,-1, ", pos= (80,110))
Self.texts = {"Elmo": text1, "Ernie": text2, "Bert": text3} # connection button and text
For eachText in [text2, text3]:
EachText.Enable (False)
For eachRadio in [radio1, radio2, radio3]: # bind event
Self.Bind (wx.EVT_RADIOBUTTON, self.OnRadio, eachRadio)
Self.selectedText = text1
Def OnRadio (self, event): # event handler
If self.selectedText:
Self.selectedText.Enable (False)
RadioSelected = event.GetEventObject ()
Text = self.texts [radioSelected.GetLabel ()]
Text.Enable (True)
Self.selectedText = text
If _ _ name__ = ='_ _ main__':
App = wx.PySimpleApp ()
RadioButtonFrame () .Show ()
App.MainLoop ()
We created radio buttons and text boxes, and then used dictionaries to establish connections between them. One for loop invalidates two text boxes, and the other for loop binds the radio button command event. When an event occurs, the currently active text box becomes invalid and the text box that matches the keyed button becomes valid.
The use of wx.RadioButton is similar to that of wx.CheckBox. Their constructors are almost the same, as follows:
Python code
Wx.RadioButton (parent, id, label, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, validator=wx.DefaultValidator, name= "radioButton")
In the check box, label is the display label for the corresponding button.
The wx.RB_GROUP style declares that the button is at the beginning of a set of radio buttons. The definition of a set of radio buttons is important because it controls switch behavior. When a button in the group is selected, the previously selected button is switched to the unselected state. After a radio button is created using wx.RB_GROUP, all subsequent radio buttons added to the same parent widget are added to the same group until another radio button is created using wx.RB_GROUP and starts the next group. In example 7.11, the first radio button is declared using wx.RB_GROUP, but not later. As a result, all the buttons are considered to be in the same group, so that when one of them is clicked, the previously selected button will be turned off.
Use the checkbox
Usually, if you want to display a set of buttons, declare that they are not the best way to do so. Instead, wxPython uses the wx.RadioBox class to allow you to create a single object that contains a complete group. As shown in figure 7.12, it looks very similar to a set of radio buttons.
Figure 7.12
To use the wx.RadioBox class, all you need is a constructor. Example 7.12 shows the code in figure 7.12.
Example 7.12 build checkbox
Python code
Import wx
Class RadioBoxFrame (wx.Frame):
Def _ init__ (self):
Wx.Frame.__init__ (self, None,-1, 'Radio Box Example'
Size= (350,200)
Panel = wx.Panel (self,-1)
SampleList = ['zero',' one', 'two',' three', 'four',' five'
'six',' seven', 'eight']
Wx.RadioBox (panel,-1, "A RadioBox", (10,10), wx.DefaultSize
SampleList, 2, wx.RA_SPECIFY_COLS)
Wx.RadioBox (panel,-1, ", (150,10), wx.DefaultSize
SampleList, 3, wx.RA_SPECIFY_COLS | wx.NO_BORDER)
If _ _ name__ = ='_ _ main__':
App = wx.PySimpleApp ()
RadioBoxFrame () .Show ()
App.MainLoop ()
The constructor of wx.RadioBox is more complex than a simple radio button because you need to specify data for all the buttons at once, as shown below:
Python code
Wx.RadioBox (parent, id, label, pos=wx.DefaultPosition
Size=wxDefaultSize, choices=None, majorDimension=0
Style=wx.RA_SPECIFY_COLS, validator=wx.DefaultValidator
Name= "radioBox")
The label parameter is static text, which is displayed on the border of the radio box. These buttons are specified using the choices parameter, which is a sequence of Python string labels.
Like the sizer of a grid, you specify the scale of the wx.RadioBox by specifying the size of one dimension, and the wxPython is automatically populated on another dimension. The main dimension of the dimension is specified using the majorDimension parameter. Which dimension is primary is determined by the style tag. The default value is wx.RA_SPECIFY_COLS. In this example, the number of columns in the left box is set to 2, and the number of columns in the right box is set to 3, and the number of rows is determined dynamically by the number of elements in the choices list. If you want the opposite behavior, you need to set the style to wx.RA_SPECIFY_ROWS. If you want to respond to a command event when a checkbox is clicked, the command event is EVT_RADIOBOX.
The wx.RadioBox class has many ways to manage the different radio buttons in the box. These methods enable you to process a specific internal button, passing the index of that button. The index starts with 0 and expands in strict order, which is the order in which the button labels are passed to the constructor. Table 7.11 lists these methods.
Table 7.11 methods for wx.RadioBox
EnableItem (n, flag): the flag parameter is a Boolean value that is used to make a button with an index n valid or invalid. To make the entire box valid immediately, use Enable ().
FindString (string): returns the integer index value of the relevant button based on the given label, or-1 if the label is not found.
GetCount (): returns the number of buttons in the box.
GetItemLabel (n) SetItemLabel (n, string): returns or sets the string label of the button with index n.
The GetSelection () GetStringSelection () SetSelection (n) SetStringSelection (string): GetSelection () and SetSelection () methods handle the integer index of the currently selected radio button. GetStringSelection () returns the string label of the currently selected button, and SetStringSelection () changes the string label of the selected button to the given value. No set * () generates an EVT_RADIOBOX event.
ShowItem (item, show): the show parameter is a Boolean value that shows or hides buttons indexed to item.
Radio buttons are not the only way to give users a range of choices. List boxes and combo boxes also take up less space and can also be configured to allow users to make multiple choices from the same group.
How do I create a list box? The list box is another mechanism that provides the user with choice. Options are placed in a rectangular window, and the user can select one or more. List boxes take up less space than radio buttons, and list boxes are a good choice when the number of items selected is relatively small. However, if the user has to pull the scroll bar far away to see all the options, then its utility is reduced. Figure 7.13 shows a wxPython list box.
In wxPython, the list box is an element of class wx.ListBox. The method of this class enables you to handle the selections in the list.
How to create a list box
Example 7.13 shows the code that produces figure 7.13.
Example 7.13 using wx.ListBox
Python code
Import wx
Class ListBoxFrame (wx.Frame):
Def _ init__ (self):
Wx.Frame.__init__ (self, None,-1, 'List Box Example'
Size= (250,200)
Panel = wx.Panel (self,-1)
SampleList = ['zero',' one', 'two',' three', 'four',' five'
'six', 'seven',' eight', 'nine',' ten', 'eleven'
'twelve',' thirteen', 'fourteen']
ListBox = wx.ListBox (panel,-1, (20,20), (80,120), sampleList
Wx.LB_SINGLE)
ListBox.SetSelection (3)
If _ _ name__ = ='_ _ main__':
App = wx.PySimpleApp ()
ListBoxFrame () .Show ()
App.MainLoop ()
The constructor of wx.ListBox is similar to that of a radio box, as follows:
Python code
Wx.ListBox (parent, id, pos=wx.DefaultPosition, size=wx.DefaultSize, choices=None, style=0, validator=wx.DefaultValidator, name= "listBox")
The main difference between a radio box and a list box is that wx.ListBox has no label attribute. The elements displayed in the list are placed in the parameter choices, which is a sequence of strings. The list box has three mutually exclusive styles that determine how the user selects elements from the list box, as described in Table 7.12.
Users usually have some problems with multiple selection, because what they generally want to see is a single selection list, which can be challenging for multiple selection (like single-choice and multiple-choice), especially for those who are easily disturbed. If you use a multi-selection list, we recommend that you clearly indicate the list.
Table 7.12 selection type style for list box
Wx.LB_EXTENDED: users can select a range of consecutive options by using shift and clicking the mouse, or use buttons with equivalent functions.
Wx.LB_MULTIPLE: users can select more than one option at a time (options can be discontiguous). In fact, in this case, the list box behaves like a set of check boxes.
Wx.LB_SINGLE: users can only choose one option at a time. In fact, in this case, the list box behaves like a set of radio buttons.
There are three styles that control the display of scroll bars in wx.ListBox, as shown in Table 7.13.
Table 7.13 Scroll bar type style for list box
Wx.LB_ALWAYS_SB: the list box will always show a vertical scroll bar, whether necessary or not.
Wx.LB_HSCROLL: if the local control supports it, the list box will create a horizontal scroll bar when there are too many selections.
Wx.LB_HSCROLL: the list box only displays a vertical scroll bar when needed. This is the default style.
There is also a style wx.LB_SORT that causes the elements in the list to be sorted alphabetically.
There are two command events specific to wx.ListBox. The EVT_LISTBOX event fires when an element in the list is selected (even if it is the currently selected element). If the list is double-clicked, the EVT_LISTBOX_DCLICK event occurs.
There are some methods specific to the list box that you can use to work with the items in the box. Table 7.14 illustrates many methods. The item index in the list box starts at 0.
Once you have a list box, you naturally want to use it with other widgets, such as drop-down menus, or check boxes. We will discuss this in the next section.
Table 7.14 method of list box
Append (item): adds a string item to the end of the list box.
Clear (): clear the list box.
Delete (n): deletes items with index n in the list box.
Deselect (n): in the multiple selection list box, causes the option at position n to be unchecked. Does not work in other styles.
FindString (string): returns the integer position of the given string, or-1 if it is not found.
GetCount (): returns the number of strings in the list.
GetSelection () SetSelection (n, select) GetStringSelection () SetStringSelection (string, select) GetSelections (): GetSelection () gets the integer index of the current selection (for radio lists only). For a multi-select list, use GetSelections () to return a tuple containing the integer location of the selected item. For radio lists, GetStringSelection () returns the currently selected string. The corresponding set method uses the Boolean parameter select to set the state of the specified string or index option. Changing the selection using this method does not trigger the EVT_LISTBOX event.
GetString (n) SetString (n, string): gets or sets the string at position n.
InsertItems (items, pos): inserts the list of strings in the parameter items before the position specified by the pos parameter in the list box. Position 0 means to place the item at the beginning of the list.
Selected (n): returns a Boolean value corresponding to the selection status of the item with index n.
Set (choices): reuse the contents of choices to set the list box.
How do I merge check boxes and list boxes? You can use the class wx.CheckListBox to merge check boxes with list boxes. Figure 7.14 shows an example of a list box and a check box merged together.
Figure 7.14
The constructor and most methods of wx.CheckListBox are the same as those of wx.ListBox. It has a new event: wx.EVT_CHECKLISTBOX, which is triggered when a check box in the list is tapped. It has two new ways to manage check boxes: Check (n, check) sets the selection status of items with an index of n, and IsChecked (item) returns True when the items of a given index are selected.
What should I do if I want a drop-down option? Drop-down selection is a selection mechanism that displays options only when the drop-down arrow is clicked. It is the simplest way to display the selected element and is most useful when the screen space is limited. Figure 7.15 shows a closed drop-down selection. Figure 7.16 shows an open drop-down selection.
Figure 7.15
Figure 7.16
The use of the drop-down selection is very similar to the standard list box. Example 7.14 shows how to create a drop-down selection.
Example 7.14
Python code
Import wx
Class ChoiceFrame (wx.Frame):
Def _ init__ (self):
Wx.Frame.__init__ (self, None,-1, 'Choice Example'
Size= (250,200)
Panel = wx.Panel (self,-1)
SampleList = ['zero',' one', 'two',' three', 'four',' five'
'six',' seven', 'eight']
Wx.StaticText (panel,-1, "Select one:", (15,20)
Wx.Choice (panel,-1, (85,18), choices=sampleList)
If _ _ name__ = ='_ _ main__':
App = wx.PySimpleApp ()
ChoiceFrame () .Show ()
App.MainLoop ()
The constructor of wx.Choice is basically the same as that of the list box:
Python code
Wx.Choice (parent, id, pos=wx.DefaultPosition, size=wx.DefaultSize, choices=None, style=0, validator=wx.DefaultValidator, name= "choice")
Wx.Choice doesn't have a specific style, but it has a unique command event: EVT_CHOICE. Almost all of the methods in Table 7.14 that apply to radio list boxes apply to wx.Choice objects.
Can I merge the text field with the list? The widget that combines a text field with a list is called a combo box, which is essentially a combination of a drop-down selection and a text box. Figure 7.17 shows a combo box.
Figure 7.17 wx.CB_DropDOWN style on the left and wx.CB_SIMPLE style on the right
On Windows, you can use the style on the right, which is a combination of a list box and a text box.
The code to create a combo box is similar to the choices we have seen. This class is wx.ComboBox, which is a subclass of wx.Choice. Example 7.15 shows the code in figure 7.17:
Example 7.15
Python code
Import wx
Class ComboBoxFrame (wx.Frame):
Def _ init__ (self):
Wx.Frame.__init__ (self, None,-1, 'Combo Box Example'
Size= (350,300)
Panel = wx.Panel (self,-1)
SampleList = ['zero',' one', 'two',' three', 'four',' five'
'six',' seven', 'eight']
Wx.StaticText (panel,-1, "Select one:", (15,15)
Wx.ComboBox (panel,-1, "default value", (15,30), wx.DefaultSize
SampleList, wx.CB_DropDOWN)
Wx.ComboBox (panel,-1, "default value", (150,30), wx.DefaultSize
SampleList, wx.CB_SIMPLE)
If _ _ name__ = ='_ _ main__':
App = wx.PySimpleApp ()
ComboBoxFrame () .Show ()
App.MainLoop ()
The constructor for wx.ComboBox is as follows:
Python code
Wx.ComboBox (parent, id, value= "", pos=wx.DefaultPosition
Size=wx.DefaultSize, choices, style=0
Validator=wx.DefaultValidator, name= "comboBox")
There are four styles for wx.ComboBox. Two of these determine how to draw a combo box: wx.CB_DropDOWN creates a combo box with a drop-down list, and wx.CB_SIMPLE creates a combo box with a list box. You can only use the wx.CB_SIMPLE style on Windows. Any combo box can be specified as a wx.CB_READONLY style, which prevents users from typing in the text field. When the combo box is specified as read-only, the choice must come from one of the elements of the selection list, even if you use the program to set it. Finally, the wx.CB_SORT style causes the elements in the selection list to appear alphabetically.
Because wx.ComboBox is a subclass of wx.Choice, all wx.Choice methods can be called by the combo box, as shown in Table 7.14. In addition, there are many methods defined to handle text components, which behave the same as wx.TextCtrl (see Table 7.4). The defined methods are Copy (), Cut (), GetInsertionPoint (), GetValue (), Paste (), Replace (from, to, text), Remove (from, to), SetInsertionPoint (pos), SetInsertionPointEnd (), and SetValue ().
After reading the above, do you have any further understanding of how to use the basic wxpython control buttons in Python? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.