2016-07-14 60 views
0

機會是我太疲倦,需要睡覺,因爲我已經做了線程前,但突然間我穿過其中規定一個常見的錯誤來的:PyQt的多線程例子

'global name 'self' is not defined'.

這裏是碼之前,我輸入線程功能,

import thread 
import time 
import ystockquote 
import Tkinter as tk 
from threadexample import * 
import sys 
from PyQt4.QtGui import * 



class Window(QtGui.QDialog): 



    def __init__(self, parent=None): 
     QtGui.QWidget.__init__(self, parent) 
     self.ui = Ui_Dialog() 
     self.ui.setupUi(self) 


     style = QStyleFactory.create('Cleanlooks') 
     app.setStyle(style) 



if __name__ == "__main__": 

    app = QtGui.QApplication(sys.argv) 
    viewer = Window() 
    viewer.show() 

    sys.exit(app.exec_()) 

和在這裏它與被稱爲(start_stream)穿線功能,

import thread 
import time 
import ystockquote 
import Tkinter as tk 
from threadexample import * 
import sys 
from PyQt4.QtGui import * 



class Window(QtGui.QDialog): 



    def __init__(self, parent=None): 
     QtGui.QWidget.__init__(self, parent) 
     self.ui = Ui_Dialog() 
     self.ui.setupUi(self) 


     style = QStyleFactory.create('Cleanlooks') 
     app.setStyle(style) 

     QtCore.QObject.connect(self.ui.startbutton, QtCore.SIGNAL('clicked()'),self.start_stream) 

    def start_stream(threadName, delay): 
     while True: 
      footsie = ystockquote.get_price('^FTSE') 
      self.ui.indexlabel.setText(footsie) 

    try: 
     thread.start_new_thread(start_stream, ("Now Streaming", 5,)) 
    except:    
     self.ui.indexlabel.setText("Error") 

    while True: 
     pass 


if __name__ == "__main__": 

    app = QtGui.QApplication(sys.argv) 
    viewer = Window() 
    viewer.show() 

    sys.exit(app.exec_()) 
+0

請編輯您的問題並修復代碼示例中的所有縮進, – ekhumoro

回答

0

的問題是在這裏:

class Window(QtGui.QDialog): 
    ... 
    def start_stream(threadName, delay): 
     ... 

start_stream缺少self參數,所以當你嘗試在方法中訪問它,self將無法​​定義。

+0

在'Window'類體中定義的try/except塊中還有一個未定義的'self'引用。跆拳道是'雖然真的:通過'在那裏?! – ekhumoro

+0

我已經嘗試將它改爲def start_stream(self,threadName,delay)並獲取Error:start_stream()需要恰好3個參數(給出2) –

+0

不要嘗試直接在類體內啓動一個線程,將它移入'__init__'或者它自己的函數,當類定義的時候評估類體,這時沒有實例。你應該使用新的['threading'](https://docs.python.org/2/library/threading.html)模塊,而不是'thread.start_new_thread'。 – mata