網站首頁 編程語言 正文
用WxPython做界面時, 如果數據操作時間比較長,會使?WxPython 界面處于假死狀態,用戶體驗非常不好。
WxPython是利用pubsub來完成消息的傳送。
下面提供一個???WxPython界面利用pubsub 展示進程工作的進度條的例子,實際使用, 只要修改?
WorkThread 里的 run 內容 及 MainFrame 里的 updateDisplay 內容即可。
環境需求
Python 3.7.3
wxPython 4.0.6
Pypubsub 4.0.3
安裝?pubsub
pip install pypubsub
# encoding: utf-8
"""
@author: 陳年椰子
@contact: hndm@qq.com
@version: 1.0
@file: wxpub.py
@time: 2020/02/25
說明 WxPython 界面利用pubsub與線程通訊使用進度條的例子
import wxpub as wp
wp.test()
"""
import wx
from pubsub import pub
from time import sleep
import threading
import sys
# 線程調用耗時長代碼
class WorkThread(threading.Thread):
def __init__(self):
"""Init Worker Thread Class."""
threading.Thread.__init__(self)
self.breakflag = False
self.start()
def stop(self):
self.breakflag = True
# 耗時長的代碼
def workproc(self):
sum_x = 0
for i in range(1, 101):
if self.breakflag:
pub.sendMessage("update", mstatus='中斷')
sleep(2)
break
sum_x = sum_x + i
sleep(0.1)
pub.sendMessage("update", mstatus='計算{} , 合計 {}'.format(i, sum_x))
return sum_x
def run(self):
"""Run Worker Thread."""
pub.sendMessage("update", mstatus='workstart')
result = self.workproc()
sleep(2)
pub.sendMessage("update", mstatus='計算完成,結果 {}'.format(result))
pub.sendMessage("update", mstatus='workdone')
class MainFrame(wx.Frame):
"""
簡單的界面
"""
def __init__(self, *args, **kw):
# ensure the parent's __init__ is called
super(MainFrame, self).__init__(*args, **kw)
# create a panel in the frame
pnl = wx.Panel(self)
# and put some text with a larger bold font on it
self.st = wx.StaticText(pnl, label="分析工具 V 2019", pos=(25,25))
font = self.st.GetFont()
font.PointSize += 5
font = font.Bold()
self.st.SetFont(font)
# create a menu bar
self.makeMenuBar()
self.gauge = wx.Gauge(self, range=100, size=(300, 20))
self.gauge.SetBezelFace(3)
self.gauge.SetShadowWidth(3)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.st, 0, wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL, 0)
sizer.Add(self.gauge, 0, wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL, 0)
self.SetSizer(sizer)
# and a status bar
self.CreateStatusBar()
self.SetStatusText("啟動完成!")
pub.subscribe(self.updateDisplay, "update")
def makeMenuBar(self):
"""
A menu bar is composed of menus, which are composed of menu items.
This method builds a set of menus and binds handlers to be called
when the menu item is selected.
"""
# Make a file menu with Hello and Exit items
fileMenu = wx.Menu()
# The "\t..." syntax defines an accelerator key that also triggers
# the same event
# helloItem = fileMenu.Append(-1, "&Hello...\tCtrl-H",
# "Help string shown in status bar for this menu item")
self.startItem = fileMenu.Append(-1, "開始",
"開始計算")
self.stopItem = fileMenu.Append(-1, "停止",
"中斷計算")
fileMenu.AppendSeparator()
self.exitItem = fileMenu.Append(-1, "退出",
"退出")
# Now a help menu for the about item
helpMenu = wx.Menu()
aboutItem = helpMenu.Append(-1, "關于",
"WxPython 界面與線程通訊的例子")
# Make the menu bar and add the two menus to it. The '&' defines
# that the next letter is the "mnemonic" for the menu item. On the
# platforms that support it those letters are underlined and can be
# triggered from the keyboard.
self.menuBar = wx.MenuBar()
self.menuBar.Append(fileMenu, "工作")
self.menuBar.Append(helpMenu, "信息")
# Give the menu bar to the frame
self.SetMenuBar(self.menuBar)
self.stopItem.Enable(False)
self.count = 0
# Finally, associate a handler function with the EVT_MENU event for
# each of the menu items. That means that when that menu item is
# activated then the associated handler functin will be called.
self.Bind(wx.EVT_MENU, self.OnStart, self.startItem)
self.Bind(wx.EVT_MENU, self.OnStop, self.stopItem)
self.Bind(wx.EVT_MENU, self.OnExit, self.exitItem)
self.Bind(wx.EVT_MENU, self.OnAbout, aboutItem)
def OnExit(self, event):
"""Close the frame, terminating the application."""
try:
self.work.stop()
except:
pass
self.Close(True)
sys.exit()
def OnStart(self, event):
self.work = WorkThread()
def OnStop(self, event):
self.work.stop()
def OnAbout(self, event):
"""Display an About Dialog"""
wx.MessageBox("分析工具 v2019",
"關于",
wx.OK|wx.ICON_INFORMATION)
def updateDisplay(self, mstatus):
"""
Receives data from thread and updates the display
"""
if mstatus.find("workstart") >= 0:
self.SetStatusText('開始計算,代碼不提供中斷線程語句,請等待計算結束!')
self.startItem.Enable(False)
self.stopItem.Enable(True)
self.exitItem.Enable(False)
if mstatus.find("workdone") >= 0:
self.SetStatusText('完成!')
self.stopItem.Enable(False)
self.startItem.Enable(True)
self.exitItem.Enable(True)
else:
self.st.SetLabel(mstatus)
if mstatus.find(",")>0 and mstatus.find("計算")>=0:
mdata = mstatus.split(',')
# 示范 , 實際使用需要傳送進度
# print(int(mdata[0].replace('計算','')))
g_count = int(mdata[0].replace('計算',''))
self.gauge.SetValue(g_count)
def test():
app = wx.App()
frm = MainFrame(None, title='分析工具')
frm.Show()
app.MainLoop()
if __name__=="__main__":
test()
運行后, 點擊 工作-開始
原文鏈接:https://blog.csdn.net/seakingx/article/details/104496005
相關推薦
- 2023-02-15 Python實現PING命令的示例代碼_python
- 2022-02-17 Flutter InAppWebView在showModalBottomSheet中無法滾動
- 2022-08-06 C語言實現UDP通信_C 語言
- 2022-03-15 this.$cookie.set(‘token‘, data.token) token賦值失效
- 2022-11-11 docker修改默認存儲位置圖文教程_docker
- 2022-09-17 C++?中封裝的含義和簡單實現方式_C 語言
- 2022-03-28 Easyx實現窗口自動碰撞的小球_C 語言
- 2022-09-14 Android自定義視圖中圖片的處理_Android
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支