wx中实现了3个线程安全的函数。如果在线程中,直接访问并更新主线程的UI,会遇到问题,有时候阻塞UI或者更新不起作用,有时严重的话会引起python崩溃。

三个安全线程如下:

  • wx.PostEvent
  • wx.CallAfter
  • wx.CallLater

其中,wx.CallLater是最抽象的线程安全函数,其次是callAfter,最后是PostEvent。

PostEvent用法:

import time
from threading import *
import wx # Button definitions
ID_START = wx.NewId()
ID_STOP = wx.NewId() # Define notification event for thread completion
EVT_RESULT_ID = wx.NewId() def EVT_RESULT(win, func):
"""Define Result Event."""
win.Connect(-1, -1, EVT_RESULT_ID, func) class ResultEvent(wx.PyEvent):
"""Simple event to carry arbitrary result data."""
def __init__(self, data):
"""Init Result Event."""
wx.PyEvent.__init__(self)
self.SetEventType(EVT_RESULT_ID)
self.data = data # Thread class that executes processing
class WorkerThread(Thread):
"""Worker Thread Class."""
def __init__(self, notify_window):
"""Init Worker Thread Class."""
Thread.__init__(self)
self.setDaemon(1)
self._notify_window = notify_window
self._want_abort = 0
# This starts the thread running on creation, but you could
# also make the GUI thread responsible for calling this
self.start() def run(self):
"""Run Worker Thread."""
# This is the code executing in the new thread. Simulation of
for i in range(10):
time.sleep(1)
if self._want_abort:
# Use a result of None to acknowledge the abort (of
# course you can use whatever you'd like or even
# a separate event type)
wx.PostEvent(self._notify_window, ResultEvent(None))
return
wx.PostEvent(self._notify_window, ResultEvent(i))
# Here's where the result would be returned (this is an
# example fixed result of the number 10, but it could be
# any Python object)
wx.PostEvent(self._notify_window, ResultEvent(10)) def abort(self):
"""abort worker thread."""
# Method for use by main thread to signal an abort
self._want_abort = 1 # GUI Frame class that spins off the worker thread
class MainFrame(wx.Frame):
"""Class MainFrame."""
def __init__(self, parent, id):
"""Create the MainFrame."""
wx.Frame.__init__(self, parent, id, 'Thread Test') # Dumb sample frame with two buttons
self.OkButton = wx.Button(self, ID_START, 'Start', pos=(0,0))
wx.Button(self, ID_STOP, 'Stop', pos=(0,50))
self.status = wx.StaticText(self, -1, '', pos=(0,100)) self.Bind(wx.EVT_BUTTON, self.OnStart, id=ID_START)
self.Bind(wx.EVT_BUTTON, self.OnStop, id=ID_STOP) # Set up event handler for any worker thread results
EVT_RESULT(self,self.OnResult) # And indicate we don't have a worker thread yet
self.worker = None def __Onfunc(self):
import time
time.sleep(10) def OnStart(self, event):
"""Start Computation."""
# Trigger the worker thread unless it's already busy
if not self.worker:
self.status.SetLabel('Starting computation')
self.worker = WorkerThread(self) def OnStop(self, event):
"""Stop Computation."""
# Flag the worker thread to stop if running
if self.worker:
self.status.SetLabel('Trying to abort computation')
self.worker.abort() def OnResult(self, event):
"""Show Result status.""" # Process results here
self.status.SetLabel('Computation Result: %s' % event.data)
# In either event, the worker is done
self.worker = None class MainApp(wx.App):
"""Class Main App."""
def OnInit(self):
"""Init Main App."""
self.frame = MainFrame(None, -1)
self.frame.Show(True)
self.SetTopWindow(self.frame)
return True if __name__ == '__main__':
app = MainApp(0)
app.MainLoop()

wxpython线程安全的方法的更多相关文章

  1. 线程的Abort方法有感

    今天看CSDN上一个很老的帖子,有个人说Thread.Abort()方法调用之后一定会抛出异常,我对这个有点疑问. 于是自己做了一个测试demo,来研究Abort抛出异常的时机.废话少说,直接上代码: ...

  2. Java中怎样创建线程安全的方法

    面试问题: 下面的方法是否线程安全?怎样让它成为线程安全的方法? class MyCounter { private static int counter = 0; public static int ...

  3. WPF / Win Form:多线程去修改或访问UI线程数据的方法( winform 跨线程访问UI控件 )

    WPF:谈谈各种多线程去修改或访问UI线程数据的方法http://www.cnblogs.com/mgen/archive/2012/03/10/2389509.html 子线程非法访问UI线程的数据 ...

  4. C#中的几个线程同步对象方法

    在编写多线程程序时无可避免会遇到线程的同步问题.什么是线程的同步呢? 举个例子:如果在一个公司里面有一个变量记录某人T的工资count=100,有两个主管A和B(即工作线程)在早一些时候拿了这个变量的 ...

  5. 多线程---其他方法 停止线程、守护线程、join方法

    第三方停止线程: 原来是stop(),因为该方法有些问题,所以被interrupt()方法取代,它的用途跟机制是 当没有指定的方式让冻结的线程恢复到运行状态时,这时需要对冻结进行清除,强制让线程恢复到 ...

  6. 线程的实现方法以及区别 extends Thread、implements Runable

    /** 线程存在于进程当中,进程由系统创建. 创建新的执行线程有两种方法 注意:   线程复写run方法,然后用start()方法调用,其实就是调用的run()方法,只是如果直接启动run()方法, ...

  7. java多线程之守护线程以及Join方法

    版权声明:本文出自汪磊的博客,转载请务必注明出处. 一.守护线程概述及示例 守护线程就是为其它线程提供"守护"作用,说白了就是为其它线程服务的,比如GC线程. java程序中线程分 ...

  8. 启动线程用start方法

    启动线程用start方法而不是用run方法 public static void main(String[] args) { Thread t=new Thread("Thread-TEST ...

  9. 线程的使用方法start run sleep join

    今天回顾了Java的线程的一些知识 例1:下面代码存有详细的解释 主要是继承Thread类与实现Runnable接口 以及start()和run()方法 package com.date0607; / ...

随机推荐

  1. sql服务器内部参数使用详情(存储过程)

    exec sp_help;返回当前数据库中的所有存储过程.exec sp_help datebase.dbo.table名称 返回当前表中的所有对象.如字段名称等.这个吊exec sp_helpfil ...

  2. 《开源分享2》:《开源框架实战宝典电子书V1.0.0》完整版!

    经过一个多月的整理,<J2EE开源框架实战宝典>--Tiny文档PDF电子书開始发放,共同拥有将近600页.为喜爱Tiny.热爱Java开源框架的朋友提供更加体贴的文档服务! 下载地址:h ...

  3. Tcpdump命令行 与 GUI Wireshark

    http://www.cnblogs.com/ggjucheng/archive/2012/01/14/2322659.html tcpdump host 192.168.1.26 and \(192 ...

  4. yii phpexcel <转>

    原文详情参见 这里 1.下载phpexcel,将压缩包中的classes复制到protected/extensions下并修改为PHPExcel. 2.修改YII配置文件config/main.php ...

  5. 【小TIP】记录各种错误【更新中】

    最好程序一遍通过,为了提高代码能力,这里将用TIP的形式记录来犯过的错误.不断更新中. *已经转移到闪存.. [150214]WA:检查是否数组开小了. [150212]WA:如果程序中有乘号,需要留 ...

  6. HDU 5033 Building(单调栈维护凸包)

    盗张图:来自http://blog.csdn.net/xuechelingxiao/article/details/39494433 题目大意:有一排建筑物坐落在一条直线上,每个建筑物都有一定的高度, ...

  7. Apache POI解析excel文件

    这里需要用到poi.jar和poi-ooxml.jar  没有的可以去http://mvnrepository.com/下载 import org.apache.poi.POIXMLDocument; ...

  8. python练习程序_员工信息表_基本实例

    python实现增删改查操作员工信息文件,可进行模糊查询: http://edu.51cto.com/lesson/id-13276.html http://edu.51cto.com/lesson/ ...

  9. python面对对象编程---------6:抽象基类

    抽象基本类的几大特点: 1:要定义但是并不完整的实现所有方法 2:基本的意思是作为父类 3:父类需要明确表示出那些方法的特征,这样在写子类时更加简单明白 用抽象基本类的地方: 1:用作父类 2:用作检 ...

  10. 数据逆向传递 unwind segue

    一.简介 unwind segue通过允许你定义一个控制器和其他控制器的关系来扩展segue的概念,这个“关系”先于顺传(流式控制)的方式.基于unwind segue可以实现导航相反的效果,即将界面 ...