Detailed explanation of wxPython library for Python GUI application development

5136cef456d144e482b1acb50e018541.jpg


 overview

 

wxPython is a powerful cross-platform GUI toolkit developed with the Python programming language and provides rich control functions. If you are a Python developer looking to create a full-featured desktop application, then wxPython is an option worth considering. wxPython is the Python binding version of the wxWidgets C++ library, which supports various operating systems, including Windows, Linux, and macOS. wxPython provides a variety of standard controls, such as buttons, text boxes, drop-down lists, menus, dialog boxes, etc., as well as many advanced controls, such as grids, tree structures, list boxes, etc., enabling developers to create complex GUI applications .


Install

Installing wxPython is very simple. Just type the following command in a terminal or command prompt:

pip install wxPython

Then you can start using wxPython to create GUI applications.

Create a GUI application

Let's look at a simple wxPython example program. The following program creates a simple window that contains a button. When the user clicks the button, the program will display a dialog box.

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(300, 200))
        self.panel = wx.Panel(self)
        self.button = wx.Button(self.panel, label="Click Me")
        self.Bind(wx.EVT_BUTTON, self.on_button_click, self.button)
        self.Show(True)

    def on_button_click(self, event):
        wx.MessageBox('Hello wxPython', 'Message', wx.OK | wx.ICON_INFORMATION)

app = wx.App(False)
frame = MyFrame(None, 'Hello wxPython')
app.MainLoop()

In this example, a class named MyFrame is first defined, which inherits from the wx.Frame class and rewrites its constructor. In the constructor, we create a wx.Panel object named panel, which is a container to contain other controls. We also create a wx.Button object called button and add it to the panel. Finally, use the Bind() method to associate the wx.EVT_BUTTON event with the on_button_click() method.
The on_button_click() method is an event handler that is called when the user clicks the button. In this method, a simple message box is created using the wx.MessageBox() method.
Finally, create a wx.App object and set its parameter to False, which means we don't want wxPython to create a console window. Then create a MyFrame object and display it.

control

wxPython supports various controls, including text boxes, buttons, drop-down lists, menus, dialog boxes, etc. The following are some commonly used wxPython controls:

wx.TextCtrl

The wx.TextCtrl control is used to display and edit text. It can be used for single line textbox or multiline textbox.

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(300, 200))
        self.panel = wx.Panel(self)
        self.textctrl = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE)

app = wx.App(False)
frame = MyFrame(None, 'TextCtrl Example')
frame.Show(True)
app.MainLoop()

In this example, we create a wx.TextCtrl object called textctrl and add it to the panel. Also use the style parameter to specify the wx.TE_MULTILINE style, which means that this text box is a multi-line text box.

wx.Button

The wx.Button control is used to create buttons.

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(300, 200))
        self.panel = wx.Panel(self)
        self.button = wx.Button(self.panel, label="Click Me")

app = wx.App(False)
frame = MyFrame(None, 'Button Example')
frame.Show(True)
app.MainLoop()

In this example, we create a wx.Button object called button and add it to the panel.

wx.StaticText

The wx.StaticText control is used to display static text.

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(300, 200))
        self.panel = wx.Panel(self)
        self.statictext = wx.StaticText(self.panel, label="Hello World")

app = wx.App(False)
frame = MyFrame(None, 'StaticText Example')
frame.Show(True)
app.MainLoop()

In this example, we create a wx.StaticText object called statictext and add it to the panel.

layout manager

wxPython supports a variety of layout managers, including BoxSizer, GridSizer, FlexGridSizer, GridBagSizer, etc. Layout managers are used to control the position and size of controls.

BoxSizer

The BoxSizer layout manager is used to arrange controls horizontally or vertically. Here is an example using the BoxSizer layout manager:

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, title):
        super(MyFrame, self).__init__(parent, title=title, size=(300, 200))

        self.InitUI()

    def InitUI(self):
        panel = wx.Panel(self)

        vbox = wx.BoxSizer(wx.VERTICAL)

        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        st = wx.StaticText(panel, label='This is a static text')
        hbox1.Add(st, proportion=1)

        vbox.Add(hbox1, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)

        hbox2 = wx.BoxSizer(wx.HORIZONTAL)
        btn1 = wx.Button(panel, label='Quit')
        btn2 = wx.Button(panel, label='Open')
        hbox2.Add(btn1, proportion=0)
        hbox2.Add(btn2, proportion=0, flag=wx.LEFT|wx.BOTTOM, border=5)

        vbox.Add(hbox2, flag=wx.ALIGN_RIGHT|wx.RIGHT, border=10)

        panel.SetSizer(vbox)

        self.Centre()
        self.Show(True)

app = wx.App(False)
frame = MyFrame(None, 'BoxSizer Example')
app.MainLoop()

In this example, a wx.Frame object is created and its title and size are set. We also create a wx.Panel object and add it to the frame. Use wx.BoxSizer(wx.VERTICAL) to create a vertical BoxSizer object and set it as the sizer of the panel.
Create two wx.BoxSizer(wx.HORIZONTAL) objects, one for placing static text controls and one for placing two button controls. Create a static text control using wx.StaticText and add it to the first horizontal BoxSizer object. Create two button controls using wx.Button and add them to the second horizontal BoxSizer object.

GridSizer

The GridSizer layout manager is used to create grid layouts. Here is an example using the GridSizer layout manager:

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(300, 200))
        self.panel = wx.Panel(self)
        grid = wx.GridSizer(2, 2, 10, 10)
        self.statictext1 = wx.StaticText(self.panel, label="Name:")
        self.statictext2 = wx.StaticText(self.panel, label="Age:")
        self.textctrl1 = wx.TextCtrl(self.panel)
        self.textctrl2 = wx.TextCtrl(self.panel)
        grid.Add(self.statictext1, 0, wx.ALIGN_RIGHT)
        grid.Add(self.textctrl1, 0, wx.EXPAND)
        grid.Add(self.statictext2, 0, wx.ALIGN_RIGHT)
        grid.Add(self.textctrl2, 0, wx.EXPAND)
        self.panel.SetSizer(grid)

app = wx.App(False)
frame = MyFrame(None, 'GridSizer Example')
frame.Show(True)
app.MainLoop()

In this example, we create a wx.GridSizer object named grid and add it to the panel. This grid layout consists of two rows and two columns with 10 pixels between each cell.

FlexGridSizer

The FlexGridSizer layout manager is used to create flexible grid layouts. It allows certain rows and/or columns to have different sizes and/or scales. Here is an example using the FlexGridSizer layout manager:

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(300, 200))
        self.panel = wx.Panel(self)
        flexgrid = wx.FlexGridSizer(2, 2, 10, 10)
        self.statictext1 = wx.StaticText(self.panel, label="Name:")
        self.statictext2 = wx.StaticText(self.panel, label="Age:")
        self.textctrl1 = wx.TextCtrl(self.panel)
        self.textctrl2 = wx.TextCtrl(self.panel)
        flexgrid.Add(self.statictext1, 0, wx.ALIGN_RIGHT)
        flexgrid.Add(self.textctrl1, 0, wx.EXPAND)
        flexgrid.Add(self.statictext2, 1, wx.ALIGN_RIGHT)
        flexgrid.Add(self.textctrl2, 1, wx.EXPAND)
        flexgrid.AddGrowableCol(1)
        self.panel.SetSizer(flexgrid)

app = wx.App(False)
frame = MyFrame(None, 'FlexGridSizer Example')
frame.Show(True)
app.MainLoop()

In this example, we create a wx.FlexGridSizer object named flexgrid and add it to the panel. This grid layout consists of two rows and two columns with 10 pixels between each cell. The second column of the first row and the second row have the same size and scale because they both used default values. However, we used the AddGrowableCol(1) method to make the second column expandable, which means that when the window is resized, the second column will grow and fill any available space.

WrapSizer

The WrapSizer layout manager is used to create automatically wrapped layouts. It allows you to add any number of controls and automatically arranges them into multiple rows. Here is an example of using the WrapSizer layout manager:

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(300, 200))
        self.panel = wx.Panel(self)
        wrapsizer = wx.WrapSizer(wx.HORIZONTAL)
        self.button1 = wx.Button(self.panel, label="Button 1")
        self.button2 = wx.Button(self.panel, label="Button 2")
        self.button3 = wx.Button(self.panel, label="Button 3")
        self.button4 = wx.Button(self.panel, label="Button 4")
        self.button5 = wx.Button(self.panel, label="Button 5")
        wrapsizer.Add(self.button1, 0, wx.EXPAND|wx.ALL, 5)
        wrapsizer.Add(self.button2, 0, wx.EXPAND|wx.ALL, 5)
        wrapsizer.Add(self.button3, 0, wx.EXPAND|wx.ALL, 5)
        wrapsizer.Add(self.button4, 0, wx.EXPAND|wx.ALL, 5)
        wrapsizer.Add(self.button5, 0, wx.EXPAND|wx.ALL, 5)
        self.panel.SetSizer(wrapsizer)

app = wx.App(False)
frame = MyFrame(None, 'WrapSizer Example')
frame.Show(True)
app.MainLoop()

In this example, we create a wx.WrapSizer object named wrapsizer and add it to the panel. This layout manager uses horizontal orientation, so when controls are added that exceed the available space, they will wrap to the next line.

ScrolledWindow

The ScrolledWindow control allows you to scroll content in windows that contain a lot of content. Here is an example using the ScrolledWindow control:

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(300, 200))
        self.panel = wx.Panel(self)
        scrolled = wx.ScrolledWindow(self.panel, -1)
        vbox = wx.BoxSizer(wx.VERTICAL)
        for i in range(30):
            label = "Line {}".format(i+1)
            statictext = wx.StaticText(scrolled, label=label)
            vbox.Add(statictext, 0, wx.EXPAND|wx.ALL, 5)
        scrolled.SetSizer(vbox)
        scrolled.SetScrollRate(0, 10)

app = wx.App(False)
frame = MyFrame(None, 'ScrolledWindow Example')
frame.Show(True)
app.MainLoop()

In this example, we create a wx.ScrolledWindow object named scrolled and add it to the panel. Created a vertical layout with 30 static text labels using wx.BoxSizer. Add a vbox layout to the scrolled window and use the SetSizer method to apply the layout to the window.
To enable scrolling, we use the SetScrollRate method to set the scrolling speed of the vertical scroll bar to 10 pixels.

GridBagSizer

The GridBagSizer layout manager allows you to lay out controls in a grid and allows you to freely control the size and position of controls in each cell. Here is an example using the GridBagSizer layout manager:

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(300, 200))
        self.panel = wx.Panel(self)
        gridbag = wx.GridBagSizer(5, 5)
        self.button1 = wx.Button(self.panel, label="Button 1")
        self.button2 = wx.Button(self.panel, label="Button 2")
        self.button3 = wx.Button(self.panel, label="Button 3")
        self.button4 = wx.Button(self.panel, label="Button 4")
        self.button5 = wx.Button(self.panel, label="Button 5")
        gridbag.Add(self.button1, pos=(0, 0), span=(1, 1), flag=wx.EXPAND|wx.ALL, border=5)
        gridbag.Add(self.button2, pos=(0, 1), span=(1, 1), flag=wx.EXPAND|wx.ALL, border=5)
        gridbag.Add(self.button3, pos=(1, 0), span=(1, 2), flag=wx.EXPAND|wx.ALL, border=5)
        gridbag.Add(self.button4, pos=(2, 0), span=(1, 1), flag=wx.EXPAND|wx.ALL, border=5)
        gridbag.Add(self.button5, pos=(2, 1), span=(1, 1), flag=wx.EXPAND|wx.ALL, border=5)
        self.panel.SetSizer(gridbag)

app = wx.App(False)
frame = MyFrame(None, 'GridBagSizer Example')
frame.Show(True)
app.MainLoop()

In this example, we create a wx.GridBagSizer object named gridbag and add it to the panel. Use the Add method to add 5 buttons to the grid, and use the pos parameter to specify the button's position in the grid, and the span parameter to specify the number of rows and columns the button spans.
We can also use the flag parameter to specify the alignment and padding of the control within the cell, and the border parameter to specify the width of the border around the control.

Color picker and file dialog

In addition to various layout managers and controls, wxPython provides some convenient dialog and utility classes for common tasks such as selecting colors or files. Here are two examples:

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(300, 200))
        self.panel = wx.Panel(self)
        self.colorbutton = wx.Button(self.panel, label="Choose Color", pos=(50, 50))
        self.filebutton = wx.Button(self.panel,label="Choose File", pos=(150, 50))
        self.colorbutton.Bind(wx.EVT_BUTTON, self.OnColor)
        self.filebutton.Bind(wx.EVT_BUTTON, self.OnFile)

    def OnColor(self, event):
        dlg = wx.ColourDialog(self.panel)
        if dlg.ShowModal() == wx.ID_OK:
            color = dlg.GetColourData().GetColour().Get()
            print("You selected color:", color)
        dlg.Destroy()

    def OnFile(self, event):
        dlg = wx.FileDialog(self.panel, "Choose a file", wildcard="*.txt")
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            print("You selected file:", path)
        dlg.Destroy()

app = wx.App(False)
frame = MyFrame(None, 'Dialogs and Tools Example')
frame.Show(True)
app.MainLoop()

In this example, we create two wx.Button objects, one for selecting a color and one for selecting a file. We add them to the panel and bind them OnColor and OnFile methods to handle click events.

When the user clicks the color selection button, we create a wx.ColourDialog object and use the GetColourData method to get the color selected by the user. When the user clicks the file selection button, we create a wx.FileDialog object and use the GetPath method to get the file path selected by the user.

Finally, this article introduces some common layout managers and controls in wxPython, and how to use dialog boxes and tool classes. Hope this article is helpful for you to learn and use wxPython.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/Rocky006/article/details/132015174