Common wxPython controls and wxpython controls
WxPython is a Python-based GUI that allows you to create graphical interface programs using Python.
In this article, we will look at the wxpython( (Chinese ). If you have any mistakes, please correct me.
Note: Downloads "or downloads related books online.
1. wx. StaticText: displays static text controls
Constructor: Wx. StaticText (parent, id, label, pos = wx. DefaultPosition, size = wx. DefaultSize, style = 0, name = "staticText ")
Example: Center_text = wx. staticText (panel,-1, "align center", (100, 50), (160,-1), wx. ALIGN_CENTER) # center-aligned text ("\ n" and other escape characters can be used in the label to control text display .)
Parameter description:
Parent: parent widget
Id: identifier. You can use-1 to automatically create a unique identifier.
Label: The text you want to display in the static control
Pos: A wx. Point or a Python tuples. It is the position of the window component.
Size: A wx. Size or a Python tuples. It is the size of a widget.
Style: style tag
Name: Object name, used for search
Style:
Wx. ALIGN_CENTER: static text is located in the center of the static text Control
Wx. ALIGN_LEFT: Left-aligned text in the widget. This is the default style.
Wx. ALIGN_RIGHT: Right-aligned text in the widget
Wx. ST_NO_AUTORESIZE: If this style is used, after SetLabel () is used to change the text, the static text control does not resize itself.
2. TextCtrl: single or multi-line text input control (single row by default. The style wx. TE_MULTILINE/wx. TE_RICH2/wx. TE_RICH can be used for multiple rows)
Constructor: Wx. textCtrl (parent, id, value = ", pos = wx. defaultPosition, size = wx. defaultSize, style = 0, validator = wx. defaultValidator, name = wx. textCtrlNameStr)
Example: Input_text = wx. TextCtrl (panel,-1, "I 've entered some text !", Size = (175,-1 ))
Single Line Text Style:
Wx. TE_CENTER: center the text in the control
Wx. TE_LEFT: Left-aligned text in the control. Default action
Wx. TE_NOHIDESEL: The text is always highlighted and only applicable to Windows
Wx. TE_PASSWORD: do not display the entered text, instead of the star number.
Wx. TE_PROCESS_ENTER: If this style is used, a text input event is triggered when you press the Enter key in the control. Otherwise, the key event is managed by the text control or the dialog box.
Wx. TE_PROCESS_TAB: If this style is specified, a common character event is created when the Tab key is pressed (generally, a Tab is inserted into the text ). Otherwise, tabs are managed by the dialog box, usually by switching between controls.
Wx. TE_READONLY: The text control is read-only and cannot be modified.
Wx. TE_RIGHT: Right-aligned text in the control
Multi-line or Rich Text styles:
Wx. HSCROLL: if the text control is multiline and the style is declared, the long lines will not wrap automatically and the horizontal scroll bar will be displayed. This option is ignored in GTK +.
Wx. TE_AUTO_URL: If Rich Text options are set and supported by the platform, this style will cause an event to be generated when the user's mouse is on a URL in the text or hitting the URL.
Wx. TE_DONTWRAP: alias of wx. HSCROLL
Wx. TE_LINEWRAP: For long lines, wrap lines with characters. Some operating systems may ignore this style.
Wx. TE_MULTILINE: The text control displays multiple lines.
Wx. TE_RICH: Used in Windows. Rich Text controls are used as basic widgets. This allows the use of style text
Wx. TE_RICH2: Used in Windows to use the latest Rich Text controls as basic widgets.
Wx. TE_WORDWRAP: For long rows, use words as the line break. Many operating systems ignore this style.
Common Text Processing Method:
AppendText (text): Add text at the end
Clear (): resets the text in the control to "" and generates a text update event.
EmulateKeyPress (event): generates a key event and inserts a controller associated with the event, just as the actual button occurs.
GetInsertionPoint ()/SetInsertionPoint (pos)/SetInsertionPointEnd (): obtains or sets the position of the insertion point, which is the index value of an integer type. The start position of the control is 0.
GetRange (from, to): returns the string within the range of the Position Index in the control.
GetSelection (): returns the index value (START, end) of the starting position of the selected text in the form of tuples)
GetStringSelection (): Get the selected string
SetSelection (from, to): Set the selected text
GetValue (): returns all strings in the control.
SetValue (value): changes all text in the control.
Remove (from, to): deletes text within a specified range.
Replace (from, to, value): Replace the text in the specified range with the given value (this can change the text length)
WriteText (text): similar to AppendText (), only the written text is placed at the current insertion point.
Multiline text processing method:
GetDefaultStyle ()/SetDefaultStyle (style): Set the text font, color, and other display styles
GetLineLength (lineNo): returns the integer of the length of the specified row.
GetLineText (lineNo): returns the text of the specified row.
GetNumberOfLines (): returns the number of rows in the control. Returns 1 for a single row.
IsMultiLine ()/IsSingleLine (): Boolean method to determine the control status
PositionToXY (pos): Specifies an integer position in the text, and returns the index position in the form of tuples (columns, rows. The index value of the column and row starts with 0.
SetStyle (start, end, style): immediately change the style of the text within the specified range
ShowPosition (pos): a multi-row control is scrolled to observe the content at the specified position.
XYToPosition (x, y): opposite to PositionToXY (pos) -- specifies the row and column, and returns the integer position.
3. wx. Button: Button control (an EVT_BUTTON command event is generated when the control is hit)
Constructor: Wx. Button (parent, id, label, pos, size = wxDefaultSize, style = 0, validator, name = "button ")
Example: Button = wx. Button (panel,-1, "Hello", pos = (50, 20 ))
4. wx. CheckBox: check box control (generate a command event of its own EVT_CHECKBOX)
Constructor: Wx. CheckBox (parent, id, label, pos = wx. DefaultPosition, size = wx. DefaultSize, style = 0, name = "checkBox ")
Example: Wx. CheckBox (panel,-1, "Alpha", (35, 40), (150, 20 ))
Solution: GetValue ()/SetValue (state)/IsChecked (): gets and sets the Switch Status of the control (values or parameters are boolean values)
5. RadioButton: Single-choice button control (generates an EVT_RADIOBUTTON event)
Constructor: Wx. RadioButton (parent, id, label, pos = wx. DefaultPosition size = wx. DefaultSize, style = 0, validator = wx. DefaultValidator, name = "radioButton ")
Example: Radio = wx. RadioButton (panel,-1, "Elmo", pos = (20, 50), style = wx. RB_GROUP)
Style: Wx. RB_GROUP style declares that the button is at the beginning of a group of radio buttons (selected ). When a button in the group is selected, the previously selected button is switched to the unselected status. Use wx. after the RB_GROUP is created, all the radio buttons that are subsequently added to the same parent widget are added to the same group until the other one uses wx. RB_GROUP is created and the next group starts.
6. wx. RadioBox: Single-choice control (a box contains a group of single-choice buttons to generate an EVT_RADIOBOX event)
Constructor: Wx. radioBox (parent, id, label, pos = wx. defaultPosition, size = wxDefaultSize, choices = None, majorDimension = 0, style = wx. RA_SPECIFY_COLS, validator = wx. defaultValidator, name = "radioBox ")
Example:
SampleList = ['zero ', 'one', 'two', 'three', 'four ', 'five', 'six', 'seven ', 'Eight '] # single-choice button label
Wx. radioBox (panel,-1, "A Radio Box", (10, 10), wx. defaultSize, sampleList, 2, wx. RA_SPECIFY_COLS) # The third parameter is the single-choice label. The second parameter is to specify two single-choice buttons for each line.
Style: Wx. RA_SPECIFY_COLS/wx. RA_SPECIFY_ROWS: Specify the dimension displayed by the single-choice button (you can specify the number of columns or rows to Display Based on the STYLE tag)
Solution:
EnableItem (n, flag): the flag parameter is a Boolean value. It is used to make the button whose index is n valid or invalid. To make the entire box valid immediately, use Enable ()
FindString (string): returns the integer index value of the related button Based on the specified tag. If the tag is not found,-1 is returned.
GetCount (): number of buttons in the return box
GetItemLabel (n)/SetItemLabel (n, string): returns or sets the string tag of the button whose index is n.
GetSelection (): returns the integer index of the currently selected radio button.
GetStringSelection (): returns the string tag of the currently selected button.
SetSelection (n): Set the integer index of the currently selected radio button
SetStringSelection (string): Set the string tag of the selected button
ShowItem (item, show): The show parameter is a Boolean value used to display or hide the buttons with the index as item.
7. wx. ListBox: list box Control
Constructor: Wx. listBox (parent, id, pos = wx. defaultPosition, size = wx. defaultSize, choices = None, style = 0, validator = wx. defaultValidator, name = "listBox ")
Example:
SampleList = ['zero ', 'one', 'two', 'three', 'four ', 'five', 'six', 'seven', 'Eight ', 'nine', 'ten ', 'even', 'twelve', 'thirteen', 'Fourteen']
ListBox = wx. ListBox (panel,-1, (20, 20), (80,120), sampleList, wx. LB_SINGLE)
Style:
Wx. LB_EXTENDED: You can use shift and mouse to select consecutive options within a certain range, or use equivalent function buttons.
Wx. LB_MULTIPLE: You can select multiple options at a time (the options can be discontinuous ). In fact, in this case, the list box acts like a set of check boxes.
Wx. LB_SINGLE: You can select only one option at a time. In fact, in this case, the list box acts like a group of radio buttons.
Wx. LB_SORT: sorts the elements in the list alphabetically.
Wx. LB_ALWAYS_SB: A vertical scroll bar is always displayed in the list box, whether necessary or not.
Wx. LB_HSCROLL: if local control is supported, a horizontal scroll bar is created when too many items are selected in the list box.
Wx. LB_HSCROLL: The list box displays a vertical scroll bar only when needed. This is the default Style
Event: The EVT_LISTBOX event is triggered 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.
Solution:
Append (item): adds a string item to the end of the list box.
Clear (): Clear the list box
Delete (n): Delete a project whose index is n in the list box.
Deselect (n): In the multi-choice list box, the option at position n is deselected. Does not work in other styles
FindString (string): returns the integer position of the given string. If no value is found,-1 is returned.
GetCount (): returns the number of strings in the list.
GetSelection (): obtains the integer index of the selected item (single-choice list)
GetStringSelection (): returns the currently selected string (single-choice list)
GetSelections (): returns the tuples that contain the specified integer (multiple-choice list)
SetSelection (n, select): sets the status of the specified index option
SetStringSelection (string, select): sets the status of the specified string option.
GetString (n): returns the string at position n.
SetString (n, string): Set the string at position n.
InsertItems (items, pos): insert the string list in the items parameter to the position specified by the pos parameter in the list box. Position 0 indicates that the project is placed at the beginning of the list.
Selected (n): returns a Boolean value corresponding to the selection Status of the project whose index is n.
Set (choices): re-use the contents of choices to Set the list box
8. wx. CheckListBox: controls that combine the check box and the list box)
Constructors and Methods: Its constructor and most of the processing methods are the same as those of the list box control.
New events: It has a new event: wx. EVT_CHECKLISTBOX, which is triggered when a check box in the list is hit.
New Method: It has two new methods to manage Check boxes: check (n, Check) sets the selection status of items indexed to n, IsChecked (item) returns True if the specified index item is selected.
9. wx. Choice: drop-down list box control (it has its own command event: EVT_CHOICE)
Constructor: Wx. choice (parent, id, pos = wx. defaultPosition, size = wx. defaultSize, choices = None, style = 0, validator = wx. defaultValidator, name = "choice ")
Example: Wx. choice (panel,-1, (85, 18), choices = ['zero ', 'one', 'two', 'three', 'four ', 'five ', 'six', 'seven', 'Eight '])
Method: Most of the methods used to set wx. ListBox as a single-choice style are applicable to this control.
10. wx. FileDialog: control of the file selection dialog box
Constructor: Wx. fileDialog (parent, message = "Choose a file", defaultDir = ", defaultFile =", wildcard = "*. * ", style = 0, pos = wx. defaultPosition)
Example: Dialog = wx. FileDialog (None, "Choose a file", OS. getcwd (), ", wildcard, wx. OPEN) # OS. getcwd () Get the current working directory
Style:
Wx. OPEN: OPEN and select a file
Wx. SAVE: used to SAVE files
Wx. HIDE_READONLY mark the dimmed check box to enable users to open files in read-only mode
The wx. MULTIPLE flag allows you to choose to open MULTIPLE files in a directory.
Wx. OVERWRITE_PROMPT: when saving the file, if the same file exists, the system prompts the user to overwrite
Wx. CHANGE_DIR: You can change the working directory of the application to the directory where the selected file is located. This makes the next file dialog box open in the same directory, without storing the value elsewhere.
Solution:
The directory, filename, style, message, and wildcard attributes of the file dialog box can be obtained and Set by using the Get/Set naming conventions.
After the user exits the dialog box, if the returned value is wx. OK, you can use the GetPath () method to get the user's selection. The returned value of this function is the full path name of a string file.
If the dialog box is an open dialog box marked with wx. MULTIPLE, use GetPaths () instead of GetPath (). This method returns a Python list of path strings.
11. wx. DirDialog: directory or folder selection dialog box Control
Constructor: Wx. dirDialog (parent, message = "Choose a directory", defaultPath = ", style = 0, pos = wx. defaultPosition, size = wx. defaultSize, name = "wxDirCtrl ")
Example: Dialog = wx. DirDialog (None, "Choose a directory:", style = wx. DD_DEFAULT_STYLE | wx. DD_NEW_DIR_BUTTON)
Style: Wx. DD_NEW_DIR_BUTTON: a button for creating a directory in the dialog box.
Processing Method: Path, message, and style attributes have the corresponding get * and set * methods. You can use the GetPath () method to obtain the user's selection after the dialog box is called.
12. wx. MessageDialog: message dialog box control (use ShowModal () to display the dialog box and return interaction results)
Constructor: Wx. MessageDialog (parent, message, caption = "Message box", style = wx. OK | wx. CANCEL, pos = wx. DefaultPosition)
Example: Dlg = wx. MessageDialog (None, "Is this explanation OK ?", 'A Message box', wx. YES_NO | wx. ICON_QUESTION)
Style:
Wx. CANCEL: contains a cancel (CANCEL) button. This button has an ID value wx. ID_CANCEL
Wx. NO_DEFAULT: In a wx. YES_NO dialog box, the No (No) button is default.
Wx. OK: contains an OK button, which has an ID value: wx. ID_ OK
Wx. YES_DEFAULT: In a wx. YES_NO dialog box, the Yes button is default. This is the default action
Wx. YES_NO: including the Yes and No buttons. Their Respective ID values are wx. ID_YES and wx. ID_NO, respectively.
Wx. ICON_ERROR: indicates an incorrect icon.
Wx. ICON_EXCLAMATION: indicates the warning icon.
Wx. ICON_HAND: Same as wx. ICON_ERROR
Wx. ICON_INFORMATION: information icon, letter I
Wx. ICON_QUESTION: Question Mark icon
Convenience function: wx. MessageBox, for example, wx. MessageBox (message, caption = "Message", style = wx. OK). The usage and style are similar to those of the wx. MessageDialog class.
13. wx. TextEntryDialog: simple input dialog box control (use ShowModal () to display the dialog box and return the interactive result)
Constructor: Wx. textEntryDialog (parent, message, caption = "Please enter text", defaultValue = ", style = wx. OK | wx. CANCEL | wx. CENTRE, pos = wx. defaultPosition) (the message parameter is a text prompt displayed in the dialog box, And the caption is displayed in the title bar. Default Value of defaultValue displayed in the text box. Style can include wx. OK and wx. CANCEL, which display the appropriate buttons)
Example: Dialog = wx. TextEntryDialog (None, "What kind of text wocould you like to enter ?", "Text Entry", "Default Value", style = wx. OK | wx. CANCEL)
Style: Several wx. TextCtrl styles can also be used here. The most useful one is wx. TE_PASSWORD, which hides the entered real password. You can also use wx. TE_MULTILINE allows you to enter multiple lines of text in the dialog box, or you can use wx. TE_LEFT, wx. TE_CENTRE, and wx. TE_RIGHT to adjust the alignment of the input text
Convenience Functions: Wx. GetTextFromUser (), wx. GetPasswordFromUser (), wx. GetNumberFromUser (), you can specify the type of the input value of the dialog box
14. wx. List dialog box Control
Constructor: Wx. SingleChoiceDialog (parent, message, caption, choices, clientData = None, style = wx. OK | wx. CANCEL | wx. CENTRE, pos = wx. DefaultPosition)
Example: Dialog = wx. SingleChoiceDialog (None, "Pick A Word", "Choices", ["Alpha", "Baker", "Charlie", "Delta"])
Solution:
SetSelection (selection): sets its default options. The selection parameter is the index value of the options.
GetSelection (): returns the index value of the selected option.
GetStringSelection (): returns the actually selected string
15. wx. ProgressDialog: control of the progress bar dialog box
Constructor: Wx. ProgressDialog (title, message, maximum = 100, parent = None, style = wx. PD_AUTO_HIDE | wx. PD_APP_MODAL)
Example: Dialog = wx. ProgressDialog ("A progress box", "Time remaining", progressMax, style = wx. PD_CAN_ABORT | wx. PD_ELAPSED_TIME | wx. PD_REMAINING_TIME)
Style:
Wx. PD_APP_MODAL: If this style is set, the progress bar is in pattern for the entire application, blocking all user events. If this style is not set, the progress bar only sets the mode for its parent window.
Wx. PD_AUTO_HIDE: The progress bar automatically hides itself until it reaches its maximum value.
Wx. PD_CAN_ABORT: Put a Cancel button on the progress bar to stop users. How to respond to cancellation from this dialog box will be described later
Wx. PD_ELAPSED_TIME: How long has this dialog box been displayed?
Wx. PD_ESTIMATED_TIME: displays the total time required to complete the progress based on the time spent, the current Count value, and the maximum counter value.
Wx. PD_REMAINING_TIME: displays the remaining time of the progress to be completed, the total time required-the time spent
Solution: Its unique method Update (value, newmsg = "). The value parameter is the new internal value of the progress bar, when update is called, the progress bar is repainted based on the ratio of the new count value to the maximum calculated value. If the optional parameter newmsg is used, the text message on the progress bar is changed to this string, which allows you to provide a text description of the current progress. This Update () method usually returns True. However, if you have canceled this dialog box by using the Cancel button, the next Update () will return False. This is your chance to respond to a user's cancellation request. To detect a user's cancellation request, we recommend that you Update () as frequently as possible ()
16. wx. GridSizer: simple layout Control
Constructor: Wx. gridSizer (rows, cols, vgap, hgap) (rows and cols are integers, they specify the size of the grid (number of rows and number of columns ), vgap and hgap allow you to determine the interval between window controls)
Note: The rows, cols, vgap, and hgap parameters all have their own get * and set * Methods: GetRows (), SetRows (rows), GetCols (), SetCols (cols ), getVGap (), SetVGap (gap), GetHGap (), and SetHGap (gap)
.
Solution:
Add (window, proportion = 0, flag = 0, border = 0, userData = None) # Add a widget at the end
Add (sizer, proportion = 0, flag = 0, border = 0, userData = None) # Add a Sizer
Add (size, proportion = 0, flag = 0, border = 0, userData = None) # Add a blank control at the end
Insert (index, window, proportion = 0, flag = 0, border = 0, userData = None) # Insert a widget
Insert (index, sizer, proportion = 0, flag = 0, border = 0, userData = None) # Insert a Sizer
Insert (index, size, proportion = 0, flag = 0, border = 0, userData = None) # Insert a blank control
Prepend (window, proportion = 0, flag = 0, border = 0, userData = None) # Add a widget at the beginning
Prepend (sizer, proportion = 0, flag = 0, border = 0, userData = None) # Add a Sizer
Prepend (size, proportion = 0, flag = 0, border = 0, userData = None) # Add a blank control at the beginning
Detach (window) # Remove a widget
Detach (sizer) # Remove a Sizer
Detach (index) # Remove a control
GetSize () and GetPosition () are used to obtain the current size and position of the sizer. The position is relative to the container associated with the sizer.
Call the SetDimension (x, y, width, height) method to specify a sizer size, so that sizer recalculates its child size based on its new size and position.
SetMinSize (width, height) and SetSizeHints (minW, minH, maxW, maxH) are used to set the minimum size. The second method enables you to specify the maximum size, GetMinSize () to access the minimum size of the entire sizer.
Set the minimum size of a child: SetItemMinSize (window, size), SetItemMinSize (sizer, size), SetItemMinSize (index, size)
Set the control border: Add (window, 0, wx. ALL | wx. EXPAND, 5), the style has wx. BOTTOM, wx. LEFT, wx. RIGHT, wx. TOP, wx. ALL, wx. EXPAND indicates expansion, that is, the original size will be maintained at the interval between controls except the border.
Dimensions and alignment styles:
Wx. ALIGN_BOTTOM: Align based on the bottom of the space (GRID) allocated by the widget
Wx. ALIGN_CENTER: place a widget so that the center of the widget is in the center of the allocated space.
Wx. ALIGN_CENTER_HORIZONTAL: horizontally centered in the grid in which it is located
Wx. ALIGN_CENTER_VERTICAL: vertical center in its grid
Wx. ALIGN_LEFT: the left edge of the grid. This is the default action
Wx. ALIGN_TOP: the top edge of the grid. This is the default action
Wx. EXPAND: fill the space in which it is located.
Wx. FIXED_MINSIZE: minimum size of fixed items
Wx. GROW: Same as wx. EXPAND. However, it is less than two characters, saving time.
Wx. SHAPED: when the size of a widget is changed, only the lattice is filled in one direction, and the other is filled in the ratio column of the original shape and size of the widget.
17. Other layout controls
Wx. FlexGridSizer (rows, cols, vgap, hgap): You can specify the sizes of each row and each column.
Specify whether rows and columns can be expanded: AddGrowableCol (idx, proportion = 0), AddGrowableRow (idx, proportion = 0)
Wx. GridBagSizer (vgap = 0, hgap = 0): You can add parts to a specified cell, and the cells can span rows and columns.
Add method: The pos parameter indicates the cell to be assigned to the window part in sizer, and the span parameter indicates the number of rows and columns that the window part should occupy.
Add (window, pos, span = wx. DefaultSpan, flag = 0, border = 0, userData = None)
Add (sizer, pos, span = wx. DefaultSpan, flag = 0, border = 0, userData = None)
Add (size, pos, span = wx. DefaultSpan, flag = 0, border = 0, userData = None)
AddItem (item)
Wx. BoxSizer (orient): orient can be wx. VERTICAL or wx. HORIZONTAL. That is, only parts can be added horizontally or vertically, and extensions can only be expanded in one direction.
Wx. StaticBoxSizer (box, orient): provides a border and text label, orient is a direction, box is a wx. BoxSizer
19. Bind event: Bind (event, handler, source = None, id = wx. ID_ANY, id2 = wx. ID_ANY). event is an event type. handler is usually a method or function.
Example: self. bind (wx. EVT_BUTTON, self. onClick, button). bind an OnClick method (defined by yourself) to the button (defined by yourself). The event type is wx. EVT_BUTTON event
18. wxPython simple application programming framework example
1 import wx 2 3 4 class NewFrame (wx. frame): 5 def _ init _ (self): 6 wx. frame. _ init _ (self, None,-1, 'title', size = (100,200) 7 panel = wx. panel (self,-1) 8 button = wx. button (panel,-1, "Close", pos = (130, 15), size = (40, 40) 9 self. bind (wx. EVT_BUTTON, self. onCloseMe, button) # bind button event 10... 11 12 def OnCloseMe (self, event): 13 self. close (True) # The Close method may continue running in the background after it is closed. You can view 14 15 def exit (self): 16 wx in the task manager. exit () # Exit application 17 18 19 if _ name _ = '_ main _': 20 newApp = wx. pySimpleApp () 21 newFrame = NewFrame () 22 newFrame. show () 23 newApp. mainLoop ()