Python - 如何显示窗口+打印文本?它只打印但不显示窗口
Posted
技术标签:
【中文标题】Python - 如何显示窗口+打印文本?它只打印但不显示窗口【英文标题】:Python - How to show the window + print the text? Where its only printing but not showing the window 【发布时间】:2012-05-31 13:35:10 【问题描述】:如何显示窗口+打印该文本?如果我有我的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)
【问题讨论】:
PyQT: How do I handle loops in main?的可能重复 @Aaron Digulla:请参见上文,应用线程无效。 【参考方案1】:几个问题: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()
【讨论】:
标签很好,我使用它是为了没有鼠标可以点击它,但需要使用键盘space
栏。
这行到底是做什么的? app.connect(app, QtCore.SIGNAL("lastWindowClosed()"), app, QtCore.SLOT("quit()"))
那一行的 lastWindowClosed() 和 quit() 在哪里?
@YumYumYum 这是来自QApplication 类的信号,它在堆栈中的最后一个窗口关闭时为类引用调用quit()
清理操作。它本质上是一种隐式清理。【参考方案2】:
lambda self: myRun()
尝试调用全局函数myRun()
。试试看
lambda myapp=myapp: myapp.myRun()
相反。奇数赋值会创建一个默认参数,因为thread.run()
没有得到一个。
【讨论】:
还是一样Traceback (most recent call last): File "/var/tmp/python-hack-the-mac/src/Test.py", line 23, in <lambda> thread.run = lambda myapp=myapp: myapp.myRun() TypeError: myRun() takes no arguments (1 given)
应该是def myRun(self):
以上是关于Python - 如何显示窗口+打印文本?它只打印但不显示窗口的主要内容,如果未能解决你的问题,请参考以下文章