1

如何显示窗口+打印该文本?如果我有我的while循环,它不再显示窗口。

import sys
import datetime
import time
from PyQt4 import QtCore, QtGui

class Main(QtGui.QMainWindow):
  def __init__(self, parent=None):
    super(Main, self).__init__(parent)       
    self.b = QtGui.QPushButton("exit", self, clicked=self.close)
    self.c = QtGui.QLabel("Test", self)

if __name__ == "__main__":
  app=QtGui.QApplication(sys.argv)
  myapp=Main()
  myapp.show()     
  while True:
    time.sleep(2)
    print "Print this + Show the Window???!!!"
  sys.exit(app.exec_())

试过:

import sys
import datetime
import time
from PyQt4 import QtCore, QtGui

class Main(QtGui.QMainWindow):
  def __init__(self, parent=None):
    super(Main, self).__init__(parent)       
    self.b = QtGui.QPushButton("exit", self, clicked=self.close)
    self.c = QtGui.QLabel("Test", self)

  def myRun():
    while True:
      time.sleep(2)
      print "Print this + Show the Window???!!!"      

if __name__ == "__main__":
  app=QtGui.QApplication(sys.argv)
  myapp=Main()
  myapp.show()     

  thread = QtCore.QThread()
  thread.run = lambda self: myRun()
  thread.start()    
  sys.exit(app.exec_())

输出:

TypeError: () 只需要 1 个参数(给定 0)

4

2 回答 2

2

几个问题:1)您没有正确调用或初始化线程。2)您需要告诉您的主线程在另一个线程运行时继续处理事件 3)您的标签悬停在“退出”按钮上,因此您将无法单击它!

import sys
import datetime
import time
from PyQt4 import QtCore, QtGui

class Main(QtGui.QMainWindow):
  def __init__(self, parent=None):
    super(Main, self).__init__(parent)       
    self.b = QtGui.QPushButton("exit", self, clicked=self.close)

  def myRun(self):
    while True:
      time.sleep(2)
      print "Print this + Show the Window???!!!"      

if __name__ == "__main__":
  app=QtGui.QApplication(sys.argv)
  myapp=Main()
  myapp.show()     

  thread = QtCore.QThread()
  thread.run = lambda myapp=myapp: myapp.myRun()
  thread.start()    

  app.connect(app, QtCore.SIGNAL("lastWindowClosed()"), app, QtCore.SLOT("quit()"))

  sys.exit(app.exec_())

  while thread.isAlive():
    #Make sure the rest of the GUI is responsive
    app.processEvents()
于 2012-05-31T14:41:38.797 回答
0

lambda self: myRun()尝试调用全局函数myRun()。尝试

lambda myapp=myapp: myapp.myRun()

反而。奇数分配将创建一个默认参数,因为thread.run()没有得到一个。

于 2012-05-31T14:36:13.800 回答