2012-05-31 116 views
1

如何顯示窗口+打印那個文本?如果我有我的while循環,它不再顯示窗口。Python - 如何顯示窗口+打印文本?哪裏只有打印但沒有顯示窗口

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_()) 

輸出:

類型錯誤:()採用完全1參數(0給出)

+0

可能重複(http://stackoverflow.com/questions/3765384/pyqt-how-do-i-handle-loops-in-main) –

+0

@Aaron Digulla:請參閱上文,不工作的應用線程。 – YumYumYum

回答

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() 
[PyQt的?如何處理迴路主]的
+0

非常感謝。 – YumYumYum

+0

標籤很好,我用它,所以沒有鼠標可以點擊它,但明確的鍵盤'空間'欄需要使用。 – YumYumYum

+0

這條線究竟做了什麼? 'app.connect(app,QtCore.SIGNAL(「lastWindowClosed()」),app,QtCore.SLOT(「quit()」))'whereWindowClose()和quit()從那一行? – YumYumYum

1

lambda self: myRun()試圖調用全局函數myRun()。嘗試

lambda myapp=myapp: myapp.myRun() 

改爲。奇怪的分配將創建一個默認參數,因爲thread.run()沒有得到一個。

+0

同樣還有'Traceback(最近調用最後一個): 文件「/var/tmp/python-hack-the-mac/src/Test.py」,第23行,在 thread.run = lambda myapp = myapp: myapp.myRun() TypeError:myRun()不帶任何參數(給出1)' – YumYumYum

+0

這應該是'def myRun(self):' –

+0

它的工作方式與你解釋過的一樣。謝謝。 – YumYumYum