Python GUI interface programming

Reference link: Python | a += b is not always a = a + b

Common GUI framework

wxPython

Install wxPython

pip install -U wxPython

C:\Users> pip install -U wxPython

Collecting wxPython

Downloading https://files.pythonhosted.org/packages/34/41/e0e109a72966f596a5b93123d94eaabd53509ef6766fa3321b4bfadbbb14/wxPython-4.0.3-cp37-cp37m-win_amd64.whl (22.7MB)

100% |████████████████████████████████| 22.7MB 819kB/s

Collecting PyPubSub (from wxPython)

Downloading https://files.pythonhosted.org/packages/ab/9e/3b50915d3346971aaa49074425788598ee4907e67c097e013f1a862bd45c/Pypubsub-4.0.0-py3-none-any.whl (63kB)

100% |████████████████████████████████| 71kB 1.5MB/s

Requirement already satisfied, skipping upgrade: six in d:\python\lib\site-packages (from wxPython) (1.11.0)

Installing collected packages: PyPubSub, wxPython

Successfully installed PyPubSub-4.0.0 wxPython-4.0.3

The two basic objects of wxPython, the application object and the top-level window:

The application object manages the main event loop, which is the driving force of the wxPython program. If there is no application object, the wxPython application will not run. The top-level window is usually used to manage the most important data, control and present it to the user.

Create a subclass of wx.App

Define the subclass wx.App Write an OnInit() initialization method in the definition subclass. Create an instance of this class in the main part of the program and call the MainLoop method of the application instance. This method transfers control of the program to wxPython

import wx # Import wxPython

class App(wx.App):

def OnInit(self): # Initialization method

frame = wx.Frame(parent=None, title='First window program') # Create top-level window

frame.Show() # Show window

return True # Return value (return to window, display on screen)

if name == 'main':

app = App() # instantiate the App class

app.MainLoop() # Call the MainLoop() main loop method of the App class

Results of the:

Use wx.App directly

Generally, if there is only one window in the system, you can use wx.App directly without creating a subclass of wx.App. This class provides a basic OnInit() initialization method.

import wx # Import wxPython

app = wx.App() # Initialize the wx.App class

frame = wx.Frame(None, title='First window program') # Define a top-level window

frame.Show() # Show window

app.MainLoop() # Call the MainLoop() main loop method of the wx.App class

Results of the:

Use wx.Frame

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

parent: The parent window of the frame. If it is a top-level window, this value is Noneid: the wxPython ID number of the new window. Usually set to -1 to let wxPython automatically generate a new IDtitle: window title pos: a wx.Point object that specifies the position of the upper left corner of the new window on the screen. In a graphical user interface program, usually (0,0) is the upper left corner of the display. This default value (-1,-1) will let the system determine the size of the window: a wx.Python object, which specifies the initial size of the window, this default value (-1,-1) will let the system determine the initial size of the window Size style: A constant that specifies the type of window. You can use the OR operation to combine them. name: The internal name of the frame. You can use it to find this window

Sample code:

import wx # Import wxPython

class MyFrame(wx.Frame):

def init(self, parent, id):

wx.Frame.init(self, parent, id, title="Create Frame", pos=(100, 100), size=(300, 300))

if name == 'main':

app = wx.App() # Initialize the application

frame = MyFrame(parent=None, id=1) # Instance MyFrame class and pass parameters

frame.Show() # Show window

app.MainLoop() # call MainLoop() main loop method

Results of the:

Common controls

StaticText text class

After creating the window, we can add some controls in the window. The so-called controls are buttons, text, input boxes, radio buttons, etc. that are frequently used.

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

parent: parent widget id: identifier. Use -1 to automatically create a unique label label: the text content displayed in the static control pos: a wx.Point or a Python tuple, which is the position of the widget size: a wx.Size or a Python tuple, It is the size of the widget style: style tag name: object name

Example code: Use wx.StaticText to output the Zen of Python

- - coding:utf-8 --

import wx

class MyFrame(wx.Frame):

def init(self, parent, id):

wx.Frame.init(self, parent, id, title="Create StaticText class",

pos=(100, 100), size=(600, 400))

panel = wx.Panel(self) # Create a drawing board

Create title and set font

title = wx.StaticText(panel, label='The Zen of Python-Tim Peters', pos=(100, 20))

font = wx.Font(16, wx.DEFAULT, wx.FONTSTYLE_NORMAL, wx.NORMAL)

title.SetFont(font)

Create text

wx.StaticText(panel, label='Beautiful is better than ugly',pos=(50, 50))

wx.StaticText(panel, label='Clear is better than obscure',pos=(50, 70))

wx.StaticText(panel, label='Simple is better than complex',pos=(50, 90))

wx.StaticText(panel, label='complex is better than messy',pos=(50, 110))

wx.StaticText(panel, label='flat is better than nested', pos=(50, 130))

wx.StaticText(panel, label='Interval is better than compact', pos=(50, 150))

wx.StaticText(panel, label='Readability is very important',pos=(50, 170))

wx.StaticText(panel, label='Even under the guise of the practicality of special cases, these rules must not be violated', pos=(50,190))

wx.StaticText(panel, label='Do not include all errors, unless you are sure you need to do this', pos=(50, 210))

wx.StaticText(panel, label='When there are multiple possibilities, don't try to guess', pos=(50, 230))

wx.StaticText(panel, label='but try to find one, preferably the only obvious solution', pos=(50, 250))

wx.StaticText(panel, label='Although this is not easy, because you are not the father of Python', pos=(50, 270))

wx.StaticText(panel, label='It might be better to do it than not to do it, but it is better not to do it without thinking about it', pos=(50, 290))

wx.StaticText(panel, label='If you can't describe your plan to people, it is definitely not a good plan; vice versa', pos=(50, 310))

wx.StaticText(panel, label='Namespace is a wonderful idea, we should use it more', pos=(50, 330))

if name == 'main':

app = wx.App() # Initialize the application

frame = MyFrame(parent=None, id=-1) # Instance MyFrame class and pass parameters

frame.Show() # Show window

app.MainLoop() # Call the main loop method

In the above code, use panel = wx.Panel(self) to create a drawing board, and use panel as the parent class, and then put the component into the form. In addition, use the wx.Font class to set the font. To create a font instance, you need to use the following constructor:

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

pointSize: the integer size of the font, in points family: used to quickly specify a font without knowing the actual name of the font style: used to specify whether the font is slanted or not weight: specify the visibility of the font underline: only valid under Windows , If the value is True, it will be underlined, if it is False, there will be no underline. faceName: specify the font name encoding: run to select one of several encodings, in most cases you can use the default encoding

Results of the:

TextCtrl input text

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

style: The style of single line wx.TextCtrl, the value is as follows:

wx.TE_CENTER: the text in the control is centered wx.TE_LEFT: the text in the control is aligned to the left wx.TE_NOHIDESEL: the text is always highlighted, only applicable to Windows wx.TE_PASSWORD: the typed text is not displayed, and wx is displayed instead of (*) .TE_PROCESS_ENTER: If the parameter is changed, when the user presses the Enter key in the control, a text input event will be triggered. Otherwise, the key event is managed by the text control or the dialog box wx.TE_PROCESS_TAB: If this style is specified, then the usual character event is created when the Tab key is pressed (generally means that a tab character will be inserted into the text). Otherwise, the tab is managed by the dialog box, usually switching between controls. wx.TE_READONLY: The text control is read-only, and the user cannot modify the text wx.TE_RIGHT: The text in the control is aligned to the right. Value: The initial text displayed in the control validator : Often used to filter data to ensure that only the data to be accepted can be entered

Sample code:

- - coding:utf-8 --

import wx

class MyFrame(wx.Frame):

def init(self, parent, id):

wx.Frame.init(self, parent, id, title="Create TextCtrl class", size=(400, 300))

#Create panel

panel = wx.Panel(self)

Create text and input box

self.title = wx.StaticText(panel, label="Please enter user name and password", pos=(140, 20))

self.label_user = wx.StaticText(panel, label="Username:", 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, pos=(50, 90), label="password:")

self.text_password = wx.TextCtrl(panel, pos=(100, 90), size=(235, 25), style=wx.TE_PASSWORD)

if name == 'main':

app = wx.App() # Initialize the application

frame = MyFrame(parent=None, id=-1) # Instance MyFrame class and pass parameters

frame.Show() # Show window

app.MainLoop() # Call the main loop method

Results of the:

Button button class

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

The parameters of wx.Button and wx.TextCtrl are basically the same, and the parameter label is the text displayed on the button

Sample code:

- - coding:utf-8 --

import wx

class MyFrame(wx.Frame):

def init(self, parent, id):

wx.Frame.init(self, parent, id, title="Create TextCtrl class", size=(400, 300))

panel = wx.Panel(self) # Create a panel

Create text and input box

self.title = wx.StaticText(panel, label="Please enter user name and password", pos=(140, 20))

self.label_user = wx.StaticText(panel, label="Username:", 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, pos=(50, 90), label="password:")

self.text_password = wx.TextCtrl(panel, pos=(100, 90), size=(235, 25), style=wx.TE_PASSWORD)

self.bt_confirm = wx.Button(panel, label='OK', pos=(105, 130)) # Create "OK" button

self.bt_cancel = wx.Button(panel, label='Cancel', pos=(195, 130)) # Create a "Cancel" button

if name == 'main':

app = wx.App() # Initialization

frame = MyFrame(parent=None, id=-1) # Instance MyFrame class and pass parameters

frame.Show() # Show window

app.MainLoop() # Call the main loop method

Results of the:

Bound event

When we click the button, we need to make the system respond accordingly, such as executing a certain judgment and giving a prompt, using the Bind() method to bind the event handler to a given event:

bt_confirm.Bind(wx.EVT_BUTTON, OnclickSubmit)

Sample code:

Click OK to determine whether the password is correct, etc.

- - coding:utf-8 --

import wx

class MyFrame(wx.Frame):

def init(self,  parent,  id):

wx.Frame.init(self, parent, id,'User Login', size=(400, 300))

Create panel

panel = wx.Panel(self)

Create "OK" and "Cancel" buttons, and bind events

self.bt_confirm = wx.Button(panel, label='OK')

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 the user name 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_password = wx.TextCtrl(panel,  style=wx.TE_PASSWORD)

Add a container, the controls in the container are arranged side by side 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_password,  proportion=1,  flag=wx.ALL,  border=5)

hsizer_button = wx.BoxSizer(wx.HORIZONTAL)

hsizer_button.Add(self.bt_confirm,  proportion=0,  flag=wx.ALIGN_CENTER,  border=5)

hsizer_button.Add(self.bt_cancel,  proportion=0,  flag=wx.ALIGN_CENTER,  border=5)

Add a container, the controls in the container are arranged side by side vertically

vsizer_all = wx.BoxSizer(wx.VERTICAL)

vsizer_all.Add(self.title,  proportion=0,  flag=wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER,

border=15)

vsizer_all.Add(hsizer_user,  proportion=0,  flag=wx.EXPAND | wx.LEFT | wx.RIGHT,  border=45)

vsizer_all.Add(hsizer_pwd,  proportion=0,  flag=wx.EXPAND | wx.LEFT | wx.RIGHT,  border=45)

vsizer_all.Add(hsizer_button,  proportion=0,  flag=wx.ALIGN_CENTER | wx.TOP,  border=15)

panel.SetSizer(vsizer_all)

def OnclickSubmit(self, event):

""" Click the OK button to execute the method """

message = ""

username = self.text_user.GetValue() # Get the entered username

password = self.text_password.GetValue() # Get the entered password

if username == "" or password == "": # Determine whether the username or password is empty

message ='Username or password cannot be empty'

elif username =='admin' and password == '123456': # username and password are correct

message ='Login successful'

else:

message ='Username and password do not match' # Username or password is wrong

wx.MessageBox(message) # Pop up a prompt box

def OnclickCancel(self, event): # If no event is clicked to cancel, an error will be reported

""" Click the cancel button to execute the method """

self.text_user.SetValue("") # Clear the entered user name

self.text_password.SetValue("") # Clear the entered password

if name == 'main':

app = wx.App() # Initialization

frame = MyFrame(parent=None, id=-1) # Instance MyFrame class and pass parameters

frame.Show() # Show window

app.MainLoop() # Call the main loop method

Results of the:

Recommended Posts

Python GUI interface programming
Python network programming
12. Network Programming in Python3
Detailed Python IO programming
Write gui in python
Talking about Python functional programming
Python programming Pycharm fast learning
Python3 script programming commonly used.md
Analysis of Python object-oriented programming
XTU programming Python training three
Black Hat Programming Application Python2
Python GUI simulation implementation calculator
Python3 interface development commonly used.md
Black hat programming application of Python1
How to understand python object-oriented programming
Python classic programming questions: string replacement
Python restful framework interface development and implementation
Analysis of common methods of Python multi-process programming