0
点赞
收藏
分享

微信扫一扫

企业微信hook接口协议,ipad协议http,语音转文字

木匠0819 2024-05-29 阅读 11

 一、ActivityIndicator介绍


主要特点

  1. 可视化活动指示器: wx.ActivityIndicator 控件以动画的形式展示活动状态,能够吸引用户注意力。
  2. 跨平台兼容性: 该控件在不同平台下都能提供一致的活动指示效果,无论是在 Windows、macOS 还是 Linux 等系统上。
  3. 简单易用: 通过简单的方法调用,可以方便地控制活动指示器的开始、停止和状态查询等操作。

使用场景

  • 后台任务指示: 在程序执行需要一段时间的后台任务时,使用活动指示器可以让用户明确地知道程序正在工作,而不是被卡住或无响应。
  • 数据加载提示: 在网络请求或大量数据加载过程中,可以使用活动指示器来提示用户数据正在加载中。

注意事项

  • 不宜滥用: 活动指示器应该在适当的情况下使用,避免在不必要的时候频繁地显示,以免影响用户体验。

二、demo源码分析


下面我们以官网给出的demo示例进行分析 

#run.py

#----------------------------------------------------------------------------
# Name:         run.py
# Purpose:      Simple framework for running individual demos
#
# Author:       Robin Dunn
#
# Created:      6-March-2000
# Copyright:    (c) 2000-2020 by Total Control Software
# Licence:      wxWindows license
#----------------------------------------------------------------------------

"""
This program will load and run one of the individual demos in this
directory within its own frame window.  Just specify the module name
on the command line.
"""

import wx
import wx.lib.inspection
import wx.lib.mixins.inspection
import sys, os

# stuff for debugging
print("Python %s" % sys.version)
print("wx.version: %s" % wx.version())
##print("pid: %s" % os.getpid()); input("Press Enter...")

assertMode = wx.APP_ASSERT_DIALOG
##assertMode = wx.APP_ASSERT_EXCEPTION


#----------------------------------------------------------------------------

class Log:
    def WriteText(self, text):
        if text[-1:] == '\n':
            text = text[:-1]
        wx.LogMessage(text)
    write = WriteText


class RunDemoApp(wx.App, wx.lib.mixins.inspection.InspectionMixin):
    def __init__(self, name, module, useShell):
        self.name = name
        self.demoModule = module
        self.useShell = useShell
        wx.App.__init__(self, redirect=False)


    def OnInit(self):
        wx.Log.SetActiveTarget(wx.LogStderr())

        self.SetAssertMode(assertMode)
        self.InitInspection()  # for the InspectionMixin base class

        frame = wx.Frame(None, -1, "RunDemo: " + self.name, size=(200,100),
                        style=wx.DEFAULT_FRAME_STYLE, name="run a sample")
        frame.CreateStatusBar()

        menuBar = wx.MenuBar()
        menu = wx.Menu()
        item = menu.Append(-1, "&Widget Inspector\tF6", "Show the wxPython Widget Inspection Tool")
        self.Bind(wx.EVT_MENU, self.OnWidgetInspector, item)
        item = menu.Append(wx.ID_EXIT, "E&xit\tCtrl-Q", "Exit demo")
        self.Bind(wx.EVT_MENU, self.OnExitApp, item)
        menuBar.Append(menu, "&File")

        ns = {}
        ns['wx'] = wx
        ns['app'] = self
        ns['module'] = self.demoModule
        ns['frame'] = frame

        frame.SetMenuBar(menuBar)
        frame.Show(True)
        frame.Bind(wx.EVT_CLOSE, self.OnCloseFrame)

        win = self.demoModule.runTest(frame, frame, Log())

        # a window will be returned if the demo does not create
        # its own top-level window
        if win:
            # so set the frame to a good size for showing stuff
            frame.SetSize((800, 600))
            win.SetFocus()
            self.window = win
            ns['win'] = win
            frect = frame.GetRect()

        else:
            # It was probably a dialog or something that is already
            # gone, so we're done.
            frame.Destroy()
            return True

        self.SetTopWindow(frame)
        self.frame = frame
        #wx.Log.SetActiveTarget(wx.LogStderr())
        #wx.Log.SetTraceMask(wx.TraceMessages)

        if self.useShell:
            # Make a PyShell window, and position it below our test window
            from wx import py
            shell = py.shell.ShellFrame(None, locals=ns)
            frect.OffsetXY(0, frect.height)
            frect.height = 400
            shell.SetRect(frect)
            shell.Show()

            # Hook the close event of the test window so that we close
            # the shell at the same time
            def CloseShell(evt):
                if shell:
                    shell.Close()
                evt.Skip()
            frame.Bind(wx.EVT_CLOSE, CloseShell)

        return True


    def OnExitApp(self, evt):
        self.frame.Close(True)


    def OnCloseFrame(self, evt):
        if hasattr(self, "window") and hasattr(self.window, "ShutdownDemo"):
            self.window.ShutdownDemo()
        evt.Skip()

    def OnWidgetInspector(self, evt):
        wx.lib.inspection.InspectionTool().Show()


#----------------------------------------------------------------------------


def main(argv):
    useShell = False
    for x in range(len(sys.argv)):
        if sys.argv[x] in ['--shell', '-shell', '-s']:
            useShell = True
            del sys.argv[x]
            break

    if len(argv) < 2:
        print("Please specify a demo module name on the command-line")
        raise SystemExit

    # ensure the CWD is the demo folder
    demoFolder = os.path.realpath(os.path.dirname(__file__))
    os.chdir(demoFolder)

    sys.path.insert(0, os.path.join(demoFolder, 'agw'))
    sys.path.insert(0, '.')

    name, ext  = os.path.splitext(argv[1])
    module = __import__(name)


    app = RunDemoApp(name, module, useShell)
    app.MainLoop()



if __name__ == "__main__":
    main(sys.argv)


run.py是运行demo的主窗体,我们暂时不需要关心。


 

 ActivityIndicator.py

# -*- coding: gbk -*-
"""
Created on 2024/5/29 15:29

@Deprecated: 
@Author: DanMo
@File : ActivityIndicator.py
"""

import wx

#----------------------------------------------------------------------

class TestPanel(wx.Panel):
    def __init__(self, parent, log):
        self.log = log
        wx.Panel.__init__(self, parent, -1)

        # Create some controls
        self.ai = wx.ActivityIndicator(self)
        self.ai.Start()
        startBtn = wx.Button(self, label='Start')
        stopBtn = wx.Button(self, label='Stop')

        # Set up the layout
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(wx.StaticText(self, label='wx.ActivityIndicator: '),
                  wx.SizerFlags().CenterVertical())
        sizer.Add(self.ai, wx.SizerFlags().Border(wx.LEFT, 10))
        sizer.Add(startBtn, wx.SizerFlags().Border(wx.LEFT, 40))
        sizer.Add(stopBtn, wx.SizerFlags().Border(wx.LEFT, 10))

        # Put it all in an outer box with a border
        box = wx.BoxSizer()
        box.Add(sizer, wx.SizerFlags(1).Border(wx.ALL, 30))
        self.SetSizer(box)

        # Set up the event handlers
        self.Bind(wx.EVT_BUTTON, self.OnStart, startBtn)
        self.Bind(wx.EVT_BUTTON, self.OnStop, stopBtn)
        self.Bind(wx.EVT_UPDATE_UI, self.OnCheckBtnStatus, startBtn)
        self.Bind(wx.EVT_UPDATE_UI, self.OnCheckBtnStatus, stopBtn)


    def OnStart(self, evt):
        self.ai.Start()


    def OnStop(self, evt):
        self.ai.Stop()


    def OnCheckBtnStatus(self, evt):
        obj = evt.GetEventObject()
        running = self.ai.IsRunning()
        if obj.Label == 'Start':
            evt.Enable(not running)
        if obj.Label == 'Stop':
            evt.Enable(running)

#----------------------------------------------------------------------

def runTest(frame, nb, log):
    win = TestPanel(nb, log)
    return win

#----------------------------------------------------------------------



overview = """<html><body>
<h2><center>wx.ActivityIndicator</center></h2>

The wx.ActivityIndicator is a small platform-specifc control showing an
animation that can be used to indicate that the program is currently busy
performing some background task.

</body></html>
"""



if __name__ == '__main__':
    import sys,os
    import run
    run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])

这段代码是一个基于 wxPython 库的简单示例,用于演示如何使用 wx.ActivityIndicator 控件来实现一个活动指示器。下面我将详细解释这段代码的设计思路和功能。

1. 导入 wxPython 库

这行代码导入了 wxPython 库,用于创建基于 wxWidgets 的桌面应用程序。

2. 定义 TestPanel 类

class TestPanel(wx.Panel):
    def __init__(self, parent, log):
        # ...

TestPanel 类继承自 wx.Panel 类,用于创建主要的用户界面面板。在 __init__ 方法中,初始化了一些控件和布局,以及事件处理函数。

3. 初始化方法

def __init__(self, parent, log):
    self.log = log
    wx.Panel.__init__(self, parent, -1)

    # 创建一些控件
    self.ai = wx.ActivityIndicator(self)
    self.ai.Start()
    startBtn = wx.Button(self, label='Start')
    stopBtn = wx.Button(self, label='Stop')

    # 设置布局
    sizer = wx.BoxSizer(wx.HORIZONTAL)
    # ... (省略部分代码)
    box = wx.BoxSizer()
    box.Add(sizer, wx.SizerFlags(1).Border(wx.ALL, 30))
    self.SetSizer(box)

    # 设置事件处理函数
    self.Bind(wx.EVT_BUTTON, self.OnStart, startBtn)
    self.Bind(wx.EVT_BUTTON, self.OnStop, stopBtn)
    self.Bind(wx.EVT_UPDATE_UI, self.OnCheckBtnStatus, startBtn)
    self.Bind(wx.EVT_UPDATE_UI, self.OnCheckBtnStatus, stopBtn)

__init__ 方法中,首先初始化了日志对象 log,然后创建了 wx.ActivityIndicator 控件、两个按钮控件,并设置了它们的布局。接着设置了按钮的事件处理函数,包括点击事件和更新 UI 事件。

4. 事件处理函数

def OnStart(self, evt):
    self.ai.Start()

def OnStop(self, evt):
    self.ai.Stop()

def OnCheckBtnStatus(self, evt):
    # ...

5. runTest 函数

def runTest(frame, nb, log):
    win = TestPanel(nb, log)
    return win

runTest 函数用于创建 TestPanel 类的实例,并返回该实例。

6. overview 变量

overview = """<html><body>
<h2><center>wx.ActivityIndicator</center></h2>

The wx.ActivityIndicator is a small platform-specifc control showing an
animation that can be used to indicate that the program is currently busy
performing some background task.

</body></html>
"""

overview 变量是一个 HTML 格式的字符串,用于提供关于 wx.ActivityIndicator 控件的概述信息。

7. 主程序入口

if __name__ == '__main__':
    import sys,os
    import run
    run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])

这部分代码是主程序的入口,用于执行整个应用程序。

以上就是这段代码的详细设计思路和讲解。通过使用 wxPython 中的 wx.ActivityIndicator 控件,可以方便地实现一个活动指示器,用于提示用户程序正在执行后台任务。

代码运行后效果如下:

点击stop后,旋转停止

举报

相关推荐

0 条评论