Location>code7788 >text

Development of cross-platform desktop applications using wxpython, dynamic tool creation handling

Popularity:281 ℃/2024-11-11 11:54:41

In our development system, often need a very easy to understand the function of the toolbar, the toolbar is a system of rapid entry, beautiful and easy to use toolbar is a system that can give the program a lot of color, this essay introduces the development of cross-platform desktop applications in the use of wxpython, the dynamic display effect of the toolbar, as well as the creation of multilevel toolbar display and so on, the processing of the creation of the toolbar.

1. wxpython toolbar introduction

In wxPython, theToolbar is a common GUI component used to display a series of icon buttons that provide users with quick access to frequently used functions.

Toolbars in wxPython can be accessed using the class to create and manage them. wxPython also provides the component that supports richer interface elements and layout features. You can choose to use it according to your needs.

Also in wxPython, the beAdvanced User Interface (AUI) library The toolbar component of the Compared to the traditionalAuiToolBar Supports advanced features such as drag and drop, floating, hiding, etc., suitable for developing more complex GUI applications.

(MacOS performance interface)

This essay focuses on an article based on the In order to process the creation of the toolbar interface, the above graphic is based on the to perform the creation.

1). Main characteristics

  • Drag and Drop Support: You can dock the toolbar to a different position by dragging it.
  • Customizable styles: Supports text, icons, separators, drop-down menus, and many other styles.
  • Can be hidden and displayed: Users can show or hide the toolbar as needed.
  • floatable: The toolbar can be floated as a separate window.

2). basic example

The following is an example of how to use the The basic example of the

import wx
import 

class MyFrame():
    def __init__(self, *args, **kw):
        super().__init__(*args, **kw)

        # Creating an AUI Manager
         = (self)

        # Create AuiToolBar
        toolbar = (self, style=.AUI_TB_DEFAULT_STYLE | .AUI_TB_OVERFLOW)

        # Add Tool Button
        open_bmp = (wx.ART_FILE_OPEN, wx.ART_TOOLBAR)
        save_bmp = (wx.ART_FILE_SAVE, wx.ART_TOOLBAR)
        exit_bmp = (wx.ART_QUIT, wx.ART_TOOLBAR)

        (wx.ID_OPEN, "Open", open_bmp, short_help="Open File")
        (wx.ID_SAVE, "Save", save_bmp, short_help="Save File")
        ()  # Adding a separator
        (wx.ID_EXIT, "Exit", exit_bmp, short_help="Exit Application")

        # Complete the toolbar layout
        ()

        # Adding Toolbars to the AUI Manager
        (toolbar, ().Name("Toolbar").Top().Dockable(True))

        # bind an event
        (wx.EVT_TOOL, self.on_open, id=wx.ID_OPEN)
        (wx.EVT_TOOL, self.on_save, id=wx.ID_SAVE)
        (wx.EVT_TOOL, self.on_exit, id=wx.ID_EXIT)

        # Settings window
        ((600, 400))
        ()
        ()  # Updating the AUI Manager

    def on_open(self, event):
        ("Open clicked", "Info",  | wx.ICON_INFORMATION)

    def on_save(self, event):
        ("Save clicked", "Info",  | wx.ICON_INFORMATION)

    def on_exit(self, event):
        ()

    def OnClose(self, event):
        ()  # Cleaning up the AUI Manager
        ()

class MyApp():
    def OnInit(self):
        frame = MyFrame(None, title="wxPython AuiToolBar Example")
        ()
        return True

if __name__ == "__main__":
    app = MyApp()
    ()

3). Main Methods and Properties

  • AddTool(id, label, bitmap, short_help="", long_help=""): Add tool buttons to the toolbar.
  • AddSeparator(): Add a separator.
  • AddControl(control): Adds a control to the toolbar, such as a text box, a drop-down box, and so on.
  • Realize(): Confirms and displays the toolbar layout.
  • SetToolDropDown(id, enable=True): Enable drop-down menu functionality for tool buttons.

4). Common Styles

A number of styling options are provided for flexible control over the appearance and behavior of the toolbar:

  • AUI_TB_TEXT: Displays the button text.
  • AUI_TB_NO_TOOLTIPS: Tooltips are not displayed.
  • AUI_TB_HORZ_LAYOUT: Horizontal layout with text to the right of the icon.
  • AUI_TB_PLAIN_BACKGROUND: Use a simple background without the default gradient effect.
  • AUI_TB_OVERFLOW: Enable overflow buttons for displaying more buttons.

Supports adding custom controls, such as drop-down boxes, text boxes, etc. You can add drop-down menu functionality to tool buttons.

AUI's toolbars can be dynamically updated, such as disabling, enabling, adding, and removing tool buttons:

5)、AUI Manager and Toolbar

AuiManager is responsible for managing all AUI components, toolbars being one of them. The toolbar can be accessed via theAuiPaneInfo Configure the toolbar's docking position, floating, hiding, and other characteristics:

pane_info = ().Name("Toolbar").Top().Caption("Main Toolbar").Floatable(True)
(toolbar, pane_info)

Provides more than the standard More powerful and flexible, especially for applications that require dynamic layouts and customizable interfaces. By means of theAuiManager Managing toolbars makes it easy to implement advanced interface features such as drag-and-drop, floating, hiding, etc., making applications more maneuverable and user-friendly.

 

2. Toolbar collapsing and secondary menu handling

For the toolbar, we generally need to create some commonly used buttons, if the interface is collapsed, the toolbar can be folded into one place, easy to view, as shown in the following interface (MacOS system performance interface).

The folding effect is the same for different platforms, as shown below for Windows.

 

And the handling of toolbars with secondary or more function points also needs to be considered, we can put them in the left side tree list for expanding more functions.

The following is shown below is that I have a secondary menu in the first level [Permission Management System], so let it open in the left side of the tree list is more intuitively reflected, the following effect is shown (Windows system performance interface).

 

3. Creation and processing of dynamic tools for system programs

The final effect of the above, we will be stored through the back-end database, dynamic display in the interface, you can assign the display according to the role of the user's rights can be.

To accomplish this, we start by defining the stored object information for the menu/toolbar as shown below.

@dataclass
class MenuInfo:
    id: str  # Menu ID
    pid: str  # Parent Menu ID
    label: str  # Menu Name
    icon: str = None  # menu icon
    path: str = None  # Menu path to locate the view
    tips: str = None  # Menu Tips
    children: list["MenuInfo"] = None

For individual toolbar messages, the following is shown.

MenuInfo(
    id="01",
    label="user management",
    icon="user",
    path="views.testaui_panel.DocumentPanel",
),

Where icon, we can just handle it according to the built-in ART_icon or our own defined collection icon. And Path is used to get the path of the form interface in the module, we dynamically build the interface class based on the path.

And for the multi-level menus displayed on the main toolbar, we also define nested collections just by using the class above, as shown below.

MenuInfo(
    id="11",
    label="privilege management system",
    icon="computer_key",
    children=[
        MenuInfo(
            id="11-1",
            label="user management",
            icon="user",
            path="views.testaui_panel.DocumentPanel",
        ),
        MenuInfo(
            id="11-2",
            label="Organizational management",
            icon="organ",
            path="views.my_banner.BannerDialog2",
        ),
        ...
    ]
}

At the initial stage of system development, we can first try to obtain the data collection in an analog way, such as through a tool to get the data, as shown below.

Above the collection of menus, we docked FastAPI SqlAlchemy interface back-end, you can dynamically get, about [FastAPI SqlAlchemy interface development], you can refer to the accompanying introduction.

Routing for Python Development Framework based on SqlAlchemy+Pydantic+FastApi

Python development framework based on SqlAlchemy+Pydantic+FastApi

Using FastAPI to develop projects, some references on how to plan the directory structure of the project and some handling of base class encapsulation.

Some conversion processing of model data and path parameters when processing data input using FastAPI

Previously introduced a little about some of the content, we follow the above to create a toolbar, as shown in the following code.

def create_toolbars(self):
    """Creating Toolbars"""
    self.tb1 = self._create_toolbar()  # toolbar (in computer software)

    (
        self.tb1,
        ()
        .Name("ToolBar1")
        .Caption("toolbar (in computer software)")
        .ToolbarPane()
        .Top()
        .Row(0)
        .Position(0)
        .Floatable(False),
    )

where mgr is our Aui interface management class, as defined below.

# Initialize AuiManager to manage toolbars, AuiNotebook, etc.
 = (self)

The processing of _create_toolbar is to get the collection of toolbars and process them dynamically, as shown in the following code.

toolbars = ToolbarUtil.create_tools()
#Iterate over the toolbar for processing
for item in toolbars:
    tool_id = ()
    help_string =  if  else 
    bitmap = get_bitmap()
    (
        tool_id=tool_id,
        label=,
        bitmap=bitmap,
        short_help_string=help_string,
    )

    # bind an event
    (
        wx.EVT_TOOL,
        partial(self.on_tool_event, item),  # Pass the menu information here
        id=tool_id,
    )

At the same time we add some common folding, about, close the window of the common toolbar, and bind the event handling, as shown in the following code.

self.Bind( wx.EVT_TOOL, lambda event: EventPub.toggle_left_panel(),id=self.id_show_hide_left)
self.Bind( wx.EVT_TOOL, lambda event: EventPub.show_about_dialog(), id=self.id_about)
self.Bind( wx.EVT_TOOL, lambda event: EventPub.close_all_page(), id=self.id_close_all)
()
return tb

For some global events, we use the pypubsub component to push and receive events.

In the following code, we define an EventPub class to handle this, as shown in the code below.

from pubsub import pub
from  import MenuInfo

# Define event handling classes to unify the handling of the event publishing interface
class EventPub:
    """Event Publisher"""

    @staticmethod
    def send_event(event_name: str, data=None):
        """Send Event"""
        (event_name, data=data)

    @staticmethod
    def show_window(data: MenuInfo, hide_toolbox=True):
        """Open window"""
        ("show_window", info=data, hide_toolbox=hide_toolbox)

      ......................

When the main form is initialized, we will track the events pushed through EventPub for processing, as follows for the unified processing of the form or dialog box, by dynamically constructing the view object, we can have it displayed inside the notbook control of the main interface.

For the following interface, we are through the dynamic path to build a unified display in the main panel, the effect is shown below.

Of course, the effect inside macOS is similar, change the form interface as shown below.