Python - 如何显示窗口+打印文本?它的唯一印刷但不显示窗口

时间:2012-05-31 13:35:11

标签: python linux pyqt pyqt4

如何显示窗口+打印该文本?如果我有我的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)

2 个答案:

答案 0 :(得分:3)

几个问题: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()

答案 1 :(得分:1)

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

lambda myapp=myapp: myapp.myRun()

代替。奇数赋值将创建一个默认参数,因为thread.run()没有得到一个。