2016-07-14 58 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