2012-10-16 97 views
3

我试图做的基本功能 后按下“启动”按钮启动计数器,按下停止按钮停止计数器, 后,但我开始处理后,它看起来像只有计数线程工作,这是不可能的按下停止按钮蟒蛇UI冻结

#!/usr/bin/python 
# -*- coding: utf-8 -*- 

import sys 
from PyQt4 import QtGui, QtCore 
from test.test_sax import start 
import time 
from threading import Thread 
import threading 
class Example(QtGui.QWidget): 
    x = 1 
    bol = True 
    def __init__(self): 
     super(Example, self).__init__() 


     self.qbtn = QtGui.QPushButton('Quit', self) 

     self.qbtn.resize(self.qbtn.sizeHint()) 
     self.qbtn.move(50, 50) 
     self.qbtn2 = QtGui.QPushButton('Start', self) 

     self.qbtn2.resize(self.qbtn2.sizeHint()) 
     self.qbtn2.move(150, 50) 

     self.qbtn.clicked.connect(self.stopCounter) 
     self.qbtn2.clicked.connect(self.startUI) 

     self.setGeometry(300, 300, 250, 150) 
     self.setWindowTitle('Quit button') 
     self.show() 
    def stopCounter(self): 
     Example.bol = False 

    def startUI(self): 
     Example.bol = True 
     thread = Thread(self.counterr()) 

    def counterr(self): 
     x = 0 
     while Example.bol: 
      print x 
      x += 1 



if __name__ == '__main__': 
    app = QtGui.QApplication(sys.argv) 
    a = Example() 
    sys.exit(app.exec_()) 

THX

+1

试试这个:你必须导入线程并开始写它。 thread.start_new_thread(self.counterr,(0,)) – fecub

回答

5

现在你骂慢功能,你甚至创建线程之前。试试这个:

thread = Thread(target=self.counterr) 
thread.start() 

在Qt应用程序,还可以考虑在QThread类,它可以运行自己的事件循环,并与你的主线程使用信号和槽沟通。

1

您正在使用Thread类完全不正确,恐怕。您传递counterr方法的结果,该方法永远不会返回。

counterr没有调用它)到Thread类作为target,然后明确启动它:

def startUI(self): 
    self.bol = True 
    thread = Thread(target=self.counterr) 
    thread.start() 

此外,刚刚访问bol作为一个实例变量,而不是一个类变量。