The wxPython framework for commonly used GUI frameworks

Keywords: Python Windows encoding Qt

1. First Identity GUI

1.1. What is a GUI

GUI is the abbreviation of Graphical User Interface.In the GUI, there are input text, return text, images such as windows, buttons, and keyboard and mouse operations.A GUI is a different way than a program.GUI programs have three basic elements: input, processing, and output.

1.2. Common GUI frameworks

python GUI development, there are many toolkits, below are some popular Toolkits

Tool kit describe
wxPython wxpython is an excellent GUI image library in python, allowing Python programmers to easily program a complete, fully functional GUI user interface
Kivy Is an open source toolkit that allows programs created from the same source code to run across platforms, with a focus on the development of programmatic user interfaces, such as multi-touch applications
Flexx Flexx is a pure python toolkit for creating graphical applications.It uses web technology to render the interface
PyQt PyQt is a python version of the Qt library and supports cross-platform
Tkinter Tkinter (also known as Tk Interface) is the standard Python interface for the Tk GUI toolkit and is a lightweight, cross-platform, open tool for image user interface (GUI)
Pywin32 Pywin32 allows you to open win32 applications in the same form as VC using Python
PyGTK PyGTK makes it easy to create programs with a graphical user interface using Python
pyui4win pyui4win is an open source interface library with self-drawing Technology

Each toolkit has its own characteristics, and the choice of toolkit depends on your application landscape.

2. Use of wxPython framework

To use the wxPython module (toolkit), you must first install the module and install it using the following commands (at the command line)

pip install -U wxPython

2.1, Create a subclass of wx.App

Before you start creating an application, create a subclass that does not have any functionality.
There are four steps to creating and using the wx.App subclass
1. Define this subclass
2. Write an OnInit() initialization method in the defined subclass
3. Create an instance of this class in the main part of the program
4. Call the Mainlop() method of the application instance, which transfers the controller that appears to wxPython.

Create a subclass with no functionality as follows

import wx   # Import wxpython
class App(wx.App):
    # Initialization Method
    def OnInit(self):
        frame = wx.Frame(parent=None, title= "Hello wxPython")     # Create windows for
        frame.Show()  # Display window
        return True  # Return value

if __name__ == '__main__':
    app = App()     # Create an instance of the APP class
    app.MainLoop()  # Call MainLoop() main loop method of App class

In the code above, the subclass App is defined, which inherits the parent wx.App

2.2. Use wx.App directly

If there is only one window in the system, wx.App is used directly by not creating a subclass of wx.App, which provides a basic OnInit() initialization method with the following code

import wx   # Import wxPython
app = wx.App()  # Initialize wx.App class
frame = wx.Frame(None, title='Hello World')  # Define a top-level window (NOne means top-level window)
frame.Show()   # Display window
app.MainLoop()  # Call MainLoop() main loop method in wx.App class

2.3. Using the wx.Frame framework

Frames in the GUI pass through what is called windows.A frame is a container that users can move around on the screen and zoom in and out. It usually contains a title bar, a menu bar, and so on.In wxPython, wxFrame is the parent of all frameworks.When creating a subclass of wx.Frame, the subclass should call its parent's constructor wx.Frame. u int_().The constructor syntax format for wx.Frame is as follows:

wx.Frame(parent, id= -1,title="",pos =wx.DefaultPosition,size=wx.DefaultSize,style=wx.DEFAULT_FRAME_STYLE,name="frame")

Parameter Description
1, parent: The parent window of the frame.If it is a top-level window, the value is None
2. id: the wxPython ID number for the new window.Typically set to -1 to have wxPython automatically generate a new ID.
3. title: Title of the window
4. pos: A wx.Point object that specifies the position of the upper left corner of the new window in the middle of the screen.In GUI programs, pass (0,0) is the upper left corner of the display.This default (-1, -1) will let the system determine the location of the window.
5. size: A wx.Size object that specifies the initial size of this window.This default (-1, -1) will let the system determine the initial size of the window
6. style: A constant specifying the window type.They can be combined using or operations
7. name: The frame's internal name can be used to find this window.

The code to create the wx.Frame subclass is as follows

import wx   # Import wxPython
class MyFrame(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, title="Establish Frame", pos=(100,100), size=(500,300))
if __name__=='__main__':
    app = wx.App()                       # Initialize application
    frame = MyFrame(parent=None, id=-1)  # Instance MyFrame and pass in parameters
    frame.Show()       # Display window
    app.MainLoop()     # Call MainLoop() main loop method

2.4. Common Controls

Controls are buttons, text, input boxes, etc. that we add to a window after it has been created.

2.41, StaticText text class

For all UI (user interface) tools, the most basic task is to draw text on the screen.In wxPython, you can use the wx.StaticText class to do this.Use wx.StaticText to change the alignment and font of text.Color, etc.
Constructor syntax format for wx.StaticText

wx.StaticText(parent,id,label,pos=wx.DefaultPosition,size=wx.DefaultSize,style=0,name="staticText")

Parameter Description
Parent:parent widget
id: Identifier.Use-1 to automatically create a unique identity
Text content that label:x displays in a static control
pos: A wx.Point or a Python tuple that is the location of the widget.
Size: A wx.Point or a Python tuple, which is the size of the widget.
Style:style Tags
Name: The name of the object

Example: using wx.StaticText outputs Python Zen (The Zen of Python)
1. After entering import this in the python console, a bunch of English will be output, which is the Zen of Python

2. Use StaticText class to output python Zen (The Zen of Python)

import wx   # Import wxPython


class MyFrame(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, title="Establish StaticText class", pos=(100, 100), size=(600, 700))
        panel = wx.Panel(self)   # Create a drawing board
        # Create a title and set the font
        title = wx.StaticText(panel, label='The Zen of Python--Tim Peters', pos=(100, 20))
        font1 = wx.Font(16, wx.DEFAULT, wx.FONTSTYLE_NORMAL, wx.NORMAL)
        title.SetFont(font1)
        # Create Text
        wx.StaticText(panel, label='Beautiful is better than ugly.', pos=(50, 50))
        wx.StaticText(panel, label='Explicit is better than implicit.', pos=(50, 70))
        wx.StaticText(panel, label='Simple is better than  complex.', pos=(50, 90))
        wx.StaticText(panel, label='Complex is better than  complicate.', pos=(50, 110))
        wx.StaticText(panel, label='Flat is better than nested.', pos=(50, 130))
        wx.StaticText(panel, label='Sparse is better than dense,', pos=(50, 150))
        wx.StaticText(panel, label='Readability counts', pos=(50, 170))
        wx.StaticText(panel, label='Special cases are not special enough to break rules.', pos=(50, 190))
        wx.StaticText(panel, label='Although practically beats purity.', pos=(50, 210))
        wx.StaticText(panel, label='Errors should never pass silently.', pos=(50, 230))
        wx.StaticText(panel, label='Unless explicitly silenced.', pos=(50, 250))
        wx.StaticText(panel, label='In the face of ambiguity, refuse the temptation to guess.', pos=(50, 270))
        wx.StaticText(panel, label='There should be one-- and preferable only one --obvious way to do it.', pos=(50, 290))
        wx.StaticText(panel, label='Although that way may not be obvious at first unless you are Dutch.', pos=(50, 310))
        wx.StaticText(panel, label='Now is better than never.', pos=(50, 330))
        wx.StaticText(panel, label='Although never is often better than *right* now.', pos=(50, 350))
        wx.StaticText(panel, label='If the implementation is hard to explain, it is a bad idea.', pos=(50, 370))
        wx.StaticText(panel, label='If the implementation is hard to explain, it is a bad idea.', pos=(50, 390))
        wx.StaticText(panel, label='If the implementation is easy to explain, it is may be a good idea.', pos=(50, 410))
        wx.StaticText(panel, label='Namespaces are one honking great idea.', pos=(50, 430))


if __name__=='__main__':
    app = wx.App()                       # Initialize application
    frame = MyFrame(parent=None, id=-1)  # Instance MyFrame and pass in parameters
    frame.Show()       # Display window
    app.MainLoop()     # Call MainLoop() main loop method

wx.Font constructor syntax

wx.Font(pointSize, family, style, weight, underline=False, faceName="",encoding=wx.FONTENCODING_DEFAULT)

Parameter Description
pointSize: The integer size of the font in points.
family: Used to quickly specify a font without knowing its specific name.
style: Indicates how striking the font is
underline: only works on Windows systems, if the value is True, with underlines, and False without underlines
faceName: Specify the font name
Encoding: Allows you to select one of several encodings, in most cases you can use the default encoding

2.42, TextCtrl input text class

The wx.StaticText class can only be used to display static text. To enter a file to interact with the user, use the wx.TextCtrl class, which allows single and multiple lines of text.It can also be used as a password entry control to mask buttons that are pressed.
Constructor syntax for wx.TextCtrl class

wx.TextCtrl(parent, id, value="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, validator=wx.DefaultValidator,name=wx.TextCtrlNameStr)

Parameter description:
Where parent,id,pos,size,style,name is the same as the wx.StaticText constructor.

value: The initial text displayed in the control
validator: Used to filter data to ensure that only data to be received can be entered.

Style: The style, values, and instructions for a single line wx.TextCtrl are as follows
1. wx.TE_CENTER: The text in the control is centered.
2. wx.TE_LEFT: Files in the control are left-aligned.
3. wx.TE_NOHIDESEL: Text is always highlighted and only applies to windows.
4. wx.TE_PASSWORD: Do not display the text you entered, replace it with an asterisk.
5. wx.TE_PROCESS_ENTER: If this parameter is used, a text entry event will be triggered when the Enter key is pressed within the control by the user.Otherwise, key events are inherently managed by the text control or the dialog box.
6. wx.TE_PROCESS_TAP: If this style is specified, the usual character event is created when the key is pressed (which typically means a tab will be inserted into the text).Otherwise, keys are managed by dialogs, usually switching between controls.
7. wx.TE_READONLY: Read-only mode
8. wx.TE_RIGHT: Right-aligned text

Example 1: Implement a login interface with a user name and password using the wx.TextCtrl and wx.StaticText classes.

import wx   # Import wxPython


class MyFrame(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, title="Establish TextCtrl class", size=(400, 300))
        panel = wx.Panel(self)  # Create a panel
        # Create text and input boxes
        self.title = wx.StaticText(panel, label="Please enter a username and password", pos=(140, 20))
        self.label_user = wx.StaticText(panel, label="User name:", pos=(50, 50))
        self.text_user = wx.TextCtrl(panel, pos=(100, 50), size=(235, 25), style=wx.TE_LEFT)
        self.label_pwd = wx.StaticText(panel, label="Password:", pos=(50, 90))
        self.text_pwd = wx.TextCtrl(panel, pos=(100, 90), size=(235, 25), style=wx.TE_PASSWORD)


if __name__ == '__main__':
    app = wx.App()           # Initialize application
    frame = MyFrame(parent=None, id=-1)    # Initialize MyFrame class and pass parameters
    frame.Show()    # Display window
    app.MainLoop()     # Call Main Loop Method

2.43, Button Button Class

Buttons are the most widely used control in GUI interfaces and are often used to capture user-generated click events.Its most obvious use is to trigger binding to a processing function

The wx.Python class library provides different types of buttons, of which the simplest and most commonly used is the wx.Button class.The constructor syntax for wx.Button is as follows:

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

Example 2: Add OK and Cancel buttons in Example 1 above

import wx


class MyFrame(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, title="Establish TextCtrl class", size=(400, 300))
        panel = wx.Panel(self)  # Create a panel
        # Create text and input boxes
        self.title = wx.StaticText(panel, label="Please enter a username and password", pos=(140, 20))
        self.label_user = wx.StaticText(panel, label="User name:", pos=(50, 50))
        self.text_user = wx.TextCtrl(panel, pos=(100, 50), size=(235, 25), style=wx.TE_LEFT)
        self.label_pwd = wx.StaticText(panel, label="Password:", pos=(50, 90))
        self.text_pwd = wx.TextCtrl(panel, pos=(100, 90), size=(235, 25), style=wx.TE_PASSWORD)
        # Create an Identify and Cancel Interface
        self.bt_confirm = wx.Button(panel, label='Determine', pos=(105, 130))
        self.bt_cancel = wx.Button(panel, label='cancel', pos=(195, 130))


if __name__ == '__main__':
    app = wx.App()           # Initialize application
    frame = MyFrame(parent=None, id=-1)    # Initialize MyFrame class and pass parameters
    frame.Show()    # Display window
    app.MainLoop()     # Call Main Loop Method

2.5, BoxSizer Layout

The above method of using coordinates is too cumbersome.There is another smarter way to lay out wxPython: sizer.Sizer is an algorithm for automatically laying out a set of window controls.
wxPython provides five sizer s, as shown in the following table

sizer name describe
BoxSizer Layout of widgets in a horizontal or vertical position.Control widgets are flexible in behavior.Usually used in nested styles, with a wide range of applications
GridSizer A basic grid layout that can be used when the widget you want to place is the same size and neatly placed in a regular grid
FlexGridSizer Some changes have been made to the GridSizer and better results can be achieved when widgets have different sizes
GridBagSizer The most flexible member in the GridSizer family.Widgets in the network can be placed freely
StaticBoxSizer A standard BoxSizer, often with a title and a loop

2.51, What is BoxSizer

Layout child widgets on a line.The layout direction of wx.BoxSizer can be horizontal or straight, and child sizer s can be included in the horizontal or straight direction to create complex layouts.Is the simplest available in wxPython.The most Linhua controls.

2.52, using BoxSizer

Dimensors manage the dimensions of a component, so they can manage the dimensions of the parent component by adding a dimensioner to the component and some layout parameters.Here's an example of using BoxSizer

import wx   # Import wxPython

class MyFrame(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, 'User Login', size = (400, 300))
        # Create a panel
        panel = wx.Panel(self)
        self.title = wx.StaticText(panel, label='Please enter a username and password')
        # Add containers in which controls are arranged vertically
        vsizer = wx.BoxSizer(wx.VERTICAL)
        vsizer.Add(self.title, proportion=0, flag=wx.BOTTOM|wx.TOP|wx.ALIGN_CENTRE, border = 15)
        panel.SetSizer(vsizer)


if __name__== '__main__':
    app = wx.App()                        # Initialization
    frame = MyFrame(parent=None, id=-1)   # Instantiate the MyFrame class and pass parameters
    frame.Show()                          # Display window
    app.MainLoop()                        # Call Main Loop Method

Add's method adds controls to the sizer
Add() Grammar Format

Box.Add(control, proportion, flag, border)

Parameter description:
1, control: Control to add

2, proportion: Controls to be added occupy a comparison of controls in the direction represented by the way they are defined.If there are three buttons, their scale values are 0,1,2, and they are all added to a horizontal batch of wx.BoxSizer with a broadband of 30. The starting width is 10. When the width of sizer changes from 30 to 30. The width of button 1 does not change to [10+(60-30)*0/(0+1+2)]=10, the width of button 2 changes to [10+(60-30)*1/(0+1+2)]=20, the width of button 3Change to [10+ (60-30)*2/(0+1+2)]=30,

3. The flag:flag parameter is used in conjunction with the border parameter to determine the margin width, with the following options
(1), wx.LEFT: left margin
(2), wx.RIGHT: Right margin
(3), wx.BOTTOM: Bottom margin
(4), wx.TOP: top margin
(5), wx.ALL: top, bottom, left, and right margins
(6), wx.LEFT: left margin

These flags can be used in conjunction with vertical line operators.The flag parameter can also be combined with the proportion s parameter to make the alignment of the control itself, including the following options
(1), wx.ALIGN_LIFT: left alignment
(2), wx.ALIGN_RIGHT: Right alignment
(3), wx.ALIGN_BOTTOM: bottom alignment
(4), wx.ALIGN_CENTER_VERTICAL: Vertical alignment
(5), wx.ALIGN_CENTER_HORIZONTAL: Horizontal alignment
(6), wx.ALIGN_CENTER: Center alignment
(7), wx.ALIGN_EXPAND: The added control will occupy all available space on the sizer positioning

4. border: Controls the margin of all added spaces by adding some pixels of white space between them

Example 3. Layout the login interface using Boxsizer

import wx   # Import wxPython

class MyFrame(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, 'User Login', size=(400, 300))
        # Create a panel
        panel = wx.Panel(self)

        # Create OK and Cancel buttons and bind events
        self.bt_confirm = wx.Button(panel, label='Determine')
        self.bt_cancel = wx.Button(panel, label='cancel')
        # Create text, left aligned
        self.title = wx.StaticText(panel, label="Please enter a username and password")
        self.label_user = wx.StaticText(panel, label="User name:")
        self.text_user = wx.TextCtrl(panel, style=wx.TE_LEFT)
        self.label_pwd = wx.StaticText(panel, label="Password:")
        self.text_pwd = wx.TextCtrl(panel, style=wx.TE_PASSWORD)
        # Add containers in which controls are arranged horizontally
        hsizer_user = wx.BoxSizer(wx.HORIZONTAL)
        hsizer_user.Add(self.label_user, proportion=0, flag=wx.ALL, border=5)
        hsizer_user.Add(self.text_user, proportion=1, flag=wx.ALL, border=5)
        hsizer_pwd = wx.BoxSizer(wx.HORIZONTAL)
        hsizer_pwd.Add(self.label_pwd, proportion=0, flag=wx.ALL, border=5)
        hsizer_pwd.Add(self.text_pwd, proportion=1, flag=wx.ALL, border=5)
        hsizer_button = wx.BoxSizer(wx.HORIZONTAL)
        hsizer_button.Add(self.bt_confirm, proportion=0, flag=wx.ALIGN_CENTRE, border=5)
        hsizer_button.Add(self.bt_cancel, proportion=0, flag=wx.ALIGN_CENTRE, border=5)

        # Add containers, in which controls are vertically arranged
        vsizer_all = wx.BoxSizer(wx.VERTICAL)
        vsizer_all.Add(self.title, proportion=0, flag=wx.BOTTOM|wx.TOP | wx.ALIGN_CENTRE, border=15)
        vsizer_all.Add(hsizer_user, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.ALIGN_RIGHT, border=45)
        vsizer_all.Add(hsizer_pwd, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.ALIGN_RIGHT, border=45)
        vsizer_all.Add(hsizer_button, proportion=0, flag=wx.ALIGN_CENTRE | wx.TOP, border=15)
        # Set the panel panel's dimension manager to vsizer_all
        panel.SetSizer(vsizer_all)


if __name__ =='__main__':
    app = wx.App()                              # Initialization
    frame = MyFrame(parent=None, id=-1)         # Instantiate and pass
    frame.Show()                                # Display window
    app.MainLoop()  

In the code above, use BoxSizer to change the absolute position to the relative position layout.

2.6. Event handling

1. An event is the address that the user executes, such as clicking a button.In the example above, once the layout is complete, you enter a username password, click the OK button to interpret the correct information, and output the corresponding prompt, which uses wx.Python's event handling.

2. By binding a function to a control that can occur when an event occurs, the function is called.Event handler functions can be bound to events using the Bind() method of the control.If you add a click event to the OK button,

bt_confirm.Bind(wx.EVT_BUTTON,OnclickSubmit)

Parameter description:
wx.EVT_BUTTON: Event type is button event.There are many event types in wxPython that start with wx.EVT_such as wx.EVT_MOTION, which results from the user moving the mouse.Types wx.ENTER_WINDOW and wx.LEAVE_WINDOW are generated when the mouse enters or leaves a window control.The type wx.EVT_MOUSEWHEEL is bound to the active event of the mouse wheel.

OnlickSubmit: Method name.Execute this method when an event occurs.
Example 4. Using events to determine user login
On the basis of the examples, click events are added to the OK and Cancel buttons, respectively.After entering the account password, click the OK button. If the user name is wr and the password is giun, the dialog box "Logon Success" will pop up. Otherwise, the dialog box "User name and password do not match", and when you click the Cancel button, the user name and password will be emptied.

import wx   # Import wxPython


class MyFrame(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, 'User Login', size=(400, 300))
        # Create a panel
        panel = wx.Panel(self)

        # Create OK and Cancel buttons and bind events
        self.bt_confirm = wx.Button(panel, label='Determine')
        self.bt_confirm.Bind(wx.EVT_BUTTON, self.OnclickSubmit)
        self.bt_cancel = wx.Button(panel, label='cancel')
        self.bt_cancel.Bind(wx.EVT_BUTTON, self.OnclickCancel)
        # Create text, left aligned
        self.title = wx.StaticText(panel, label="Please enter a username and password")
        self.label_user = wx.StaticText(panel, label="User name:")
        self.text_user = wx.TextCtrl(panel, style=wx.TE_LEFT)
        self.label_pwd = wx.StaticText(panel, label="Password:")
        self.text_pwd = wx.TextCtrl(panel, style=wx.TE_PASSWORD)
        # Add containers in which controls are arranged horizontally
        hsizer_user = wx.BoxSizer(wx.HORIZONTAL)
        hsizer_user.Add(self.label_user, proportion=0, flag=wx.ALL, border=5)
        hsizer_user.Add(self.text_user, proportion=1, flag=wx.ALL, border=5)
        hsizer_pwd = wx.BoxSizer(wx.HORIZONTAL)
        hsizer_pwd.Add(self.label_pwd, proportion=0, flag=wx.ALL, border=5)
        hsizer_pwd.Add(self.text_pwd, proportion=1, flag=wx.ALL, border=5)
        hsizer_button = wx.BoxSizer(wx.HORIZONTAL)
        hsizer_button.Add(self.bt_confirm, proportion=0, flag=wx.ALIGN_CENTRE, border=5)
        hsizer_button.Add(self.bt_cancel, proportion=0, flag=wx.ALIGN_CENTRE, border=5)

        # Add containers, in which controls are vertically arranged
        vsizer_all = wx.BoxSizer(wx.VERTICAL)
        vsizer_all.Add(self.title, proportion=0, flag=wx.BOTTOM | wx.TOP | wx.ALIGN_CENTRE, border=15)
        vsizer_all.Add(hsizer_user, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.ALIGN_RIGHT, border=45)
        vsizer_all.Add(hsizer_pwd, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.ALIGN_RIGHT, border=45)
        vsizer_all.Add(hsizer_button, proportion=0, flag=wx.ALIGN_CENTRE | wx.TOP, border=15)
        # Set the panel panel's dimension manager to vsizer_all
        panel.SetSizer(vsizer_all)

    def OnclickSubmit(self, event):
        """ Click the OK button to execute the method """
        message = ""
        username = self.text_user.GetValue()    # Get input user name
        password = self.text_pwd.GetValue()     # Get the password you entered
        if username == 'wr' and password == 'giun':
            message = "Login Successful"
        else:
            message = "User name and password do not match"
        wx.MessageBox(message)

    def OnclickCancel(self, event):
        """ Click the Cancel button to execute the method """
        self.text_user.SetValue("")
        self.text_pwd.SetValue("")


if __name__ == '__main__':
    app = wx.App()          # Initialize application
    frame = MyFrame(parent=None, id=-1)  # Instantiate and pass
    frame.Show()   # Display window
    app.MainLoop()  # Call Main Loop Method

Posted by ungown_admin on Tue, 13 Aug 2019 18:31:43 -0700