【问题标题】:python UI freezingpython UI冻结
【发布时间】:2012-10-16 09:05:21
【问题描述】:

我正在尝试制作基本功能 按下“开始”按钮后开始计数器,按下停止按钮后停止计数器, 但是在我开始进程后,似乎只有计数线程在工作,并且无法按下停止按钮

#!/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_())

谢谢

【问题讨论】:

  • 试试这个:你必须导入线程并启动它写这个。 thread.start_new_thread(self.counterr, (0, ))

标签: python multithreading user-interface


【解决方案1】:

现在,您甚至在创建线程之前就调用了慢速函数。试试这个:

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

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

【讨论】:

    【解决方案2】:

    恐怕您完全错误地使用了Thread 类。您将 counterr 方法的 result 传递给它,该方法永远不会返回。

    counterr调用它)作为target传递给Thread类,然后显式启动它:

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

    另外,只需将bol 作为实例变量访问,而不是类变量。

    【讨论】:

      猜你喜欢
      • 2022-01-25
      • 2015-01-16
      • 2019-09-16
      • 1970-01-01
      • 2015-04-20
      • 1970-01-01
      • 1970-01-01
      • 2014-07-30
      相关资源
      最近更新 更多