wxPython Demo大全系列:ActivityIndicator控件分析

news/2024/10/20 21:28:40/

 一、ActivityIndicator介绍


wx.ActivityIndicator 控件是 wxPython 中用于显示活动指示器的控件,通常用于指示程序正在执行某些后台任务或操作。它在用户界面中以动画的形式表现出活动状态,让用户知道应用程序正在进行处理而不是被挂起。

主要特点

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

使用场景

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

注意事项

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

二、demo源码分析


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

python">#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 = WriteTextclass RunDemoApp(wx.App, wx.lib.mixins.inspection.InspectionMixin):def __init__(self, name, module, useShell):self.name = nameself.demoModule = moduleself.useShell = useShellwx.App.__init__(self, redirect=False)def OnInit(self):wx.Log.SetActiveTarget(wx.LogStderr())self.SetAssertMode(assertMode)self.InitInspection()  # for the InspectionMixin base classframe = 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'] = wxns['app'] = selfns['module'] = self.demoModulens['frame'] = frameframe.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 windowif win:# so set the frame to a good size for showing stuffframe.SetSize((800, 600))win.SetFocus()self.window = winns['win'] = winfrect = frame.GetRect()else:# It was probably a dialog or something that is already# gone, so we're done.frame.Destroy()return Trueself.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 windowfrom wx import pyshell = py.shell.ShellFrame(None, locals=ns)frect.OffsetXY(0, frect.height)frect.height = 400shell.SetRect(frect)shell.Show()# Hook the close event of the test window so that we close# the shell at the same timedef CloseShell(evt):if shell:shell.Close()evt.Skip()frame.Bind(wx.EVT_CLOSE, CloseShell)return Truedef 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 = Falsefor x in range(len(sys.argv)):if sys.argv[x] in ['--shell', '-shell', '-s']:useShell = Truedel sys.argv[x]breakif len(argv) < 2:print("Please specify a demo module name on the command-line")raise SystemExit# ensure the CWD is the demo folderdemoFolder = 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

python"># -*- 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 = logwx.Panel.__init__(self, parent, -1)# Create some controlsself.ai = wx.ActivityIndicator(self)self.ai.Start()startBtn = wx.Button(self, label='Start')stopBtn = wx.Button(self, label='Stop')# Set up the layoutsizer = 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 borderbox = wx.BoxSizer()box.Add(sizer, wx.SizerFlags(1).Border(wx.ALL, 30))self.SetSizer(box)# Set up the event handlersself.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,osimport runrun.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])

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

1. 导入 wxPython

 import wx

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

2. 定义 TestPanel 类

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

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

3. 初始化方法

python">def __init__(self, parent, log):self.log = logwx.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. 事件处理函数

python">def OnStart(self, evt):self.ai.Start()def OnStop(self, evt):self.ai.Stop()def OnCheckBtnStatus(self, evt):# ...

5. runTest 函数

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

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

6. overview 变量

python">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. 主程序入口

python">if __name__ == '__main__':import sys,osimport runrun.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])

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

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

代码运行后效果如下:

点击stop后,旋转停止


http://www.ppmy.cn/news/1464916.html

相关文章

Spring Boot + Spring Security + JWT 从零开始

Spring Boot + Spring Security + JWT 从零开始 这篇笔记中,我们将学习如何从头开始设置一个带有Spring Security的Spring Boot应用程序,它连接到一个LDAP身份验证的Spring Security身份验证提供程序,这将是即将出现的,这个连接和工作都是开箱即用的。 实际上,设置这个非…

0基础认识C语言(理论+实操 2)

小伙伴们大家好&#xff0c;今天也要撸起袖子加油干&#xff01;万事开头难&#xff0c;越学到后面越轻松~ 话不多说&#xff0c;开始正题~ 前提回顾&#xff1a; 接上次博客&#xff0c;我们学到了转义字符&#xff0c;最后留下两个转义字符不知道大家有没有动手尝试了一遍&a…

开源一个工厂常用的LIMS系统

Senaite是一款强大且可靠的基于Web的LIMS/LIS系统&#xff0c;采用Python编写&#xff0c;构建在Plone CMS基础架构之上。该系统处于积极开发阶段&#xff0c;在灵活的定制空间中为开发人员提供了丰富的功能。其中&#xff0c;Senaite在处理REST的JSON API上做得出色&#xff0…

STM32实验之USART串口发送+接受数据(二进制/HEX/文本)

涉及三个实验&#xff1a; 1.USART串口发送和接收数据 我们使用的是将串口封装成为一个Serial.c模块.其中包含了 void Serial_Init(void);//串口初始化 void Serial_SendByte(uint8_t Byte);//串口发送一个字节 void Serial_SendArray(uint8_t *Array,uint16_t Length);//…

【408真题】2009-27

“接”是针对题目进行必要的分析&#xff0c;比较简略&#xff1b; “化”是对题目中所涉及到的知识点进行详细解释&#xff1b; “发”是对此题型的解题套路总结&#xff0c;并结合历年真题或者典型例题进行运用。 涉及到的知识全部来源于王道各科教材&#xff08;2025版&…

在Go语言中如何实现变参函数和函数选项模式

在Go语言编程中,我们经常会遇到需要给函数传递可选参数的情况。传统的做法是定义一个结构体,将所有可选参数作为结构体字段,然后在调用函数时创建该结构体的实例并传递。这种方式虽然可行,但是当可选参数较多时,创建结构体实例的代码就会变得冗长และ不太直观。 Go语言的一个…

随机链表的复制

后插节点解答 实现目标&#xff0c;要将复杂问题拆解为较为解决的较小问题进行逐步解决。可以将要复制的链表分为节点插入到每个原链表的节点后面&#xff0c;如图所示&#xff1a; 1.插入复制节点 想要实现如图所示效果&#xff0c;首先用malloc创建节点&#xff0c;然…

Textual for Mac:轻量级IRC客户端

在寻找一款高效、轻量级的IRC客户端时&#xff0c;Textual for Mac无疑是你的不二之选。它集成了众多现代技术&#xff0c;如本机IPv6、最新的IRCv3规范&#xff0c;以及客户端证书身份验证&#xff0c;让你的聊天体验更加顺畅和安全。 Textual for Mac v7.2.2免激活版下载 Tex…