版权声明:原创作品,欢迎转发!转发附上链接 https://blog.csdn.net/qq_26369907/article/details/90408513
在用wxpython做UI时跳进了一个坑,在此记录。
小结:
1.学习语言时先查询该语言是否本身自带有某模块。例如python3多线程threading功能强大,结合jion()和setDaemon()函数使用更灵活,使用多线程时首先想到了threading, 但wxpython是用python写的一个UI框架,其本身自带有多线程函数:
- wx.PostEvent
- wx.CallAfter
- wx.CallLater
舍去这三个,直接使用threading导致UI出现卡顿,卡死等情况。结合wxpython自带的多线程函数效果很好。
2. 使用多线程做UI时,建议主线程进行UI相关的显示数据绘制,而且子线程只进行逻辑处理。例如:wxPython中子线程调用方法wx.CallAfter()之后,主线程的UI可以在当前事件处理结束后处理子线程发送的消息,这是wxPython中子线程给主线程发送消息最简单的方法。
案例
实现在主线程开始计时,子线程输出进度条。
# coding = utf-8
import wx
import time
import threading
class ProgressBarThread(threading.Thread):
"""进度条类 """
def __init__(self, parent):
"""
:param parent: 主线程UI
:param timer: 计时器
"""
super(ProgressBarThread, self).__init__() # 继承
self.parent = parent
self.setDaemon(True) # 设置为守护线程, 即子线程是守护进程,主线程结束子线程也随之结束。
def run(self):
count = 0
while count < 5:
count = count + 0.5
time.sleep(0.5)
wx.CallAfter(self.parent.update_process_bar, count) # 更新进度条进度
wx.CallAfter(self.parent.close_process_bar) # destroy进度条
class CounterThread(threading.Thread):
“”计时类“”
def __init__(self, parent):
super(CounterThread, self).__init__()
self.parent = parent
self.setDaemon(True)
def run(self):
i = 0
while i < 5:
i += 1
print(i)
time.sleep(1)
class AppUI(wx.Frame):
def __init__(self, parent, title="test thread"):
wx.Frame.__init__(self, parent, title=title)
self.Center()
self.panel = wx.Panel(parent=self)
self.button_panel = wx.Panel(self.panel)
self.button_start = wx.Button(self.panel, wx.ID_ANY, label="开始")
self.button_start.Bind(wx.EVT_BUTTON, self.on_click_start)
self.dialog = None
def update_process_bar(self, count):
self.dialog.Update(count)
def close_process_bar(self):
self.dialog.Destroy()
def on_click_start(self, evt):
self.dialog = wx.ProgressDialog("录音进度", "Time remaining", 5, style=wx.PD_AUTO_HIDE | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME)
self.progress_1 = ProgressBarThread(self)
self.progress_1.start()
self.counter = CounterThread(self)
self.counter.start()
if __name__ == "__main__":
app = wx.App(False)
AppUI(None).Show()
app.MainLoop()
UI图:
参考链接:
https://www.blog.pythonlibrary.org/2010/05/22/wxpython-and-threads/
https://blog.csdn.net/fengmm521/article/details/78446413