2016-03-20 38 views
-2

为什么这两个函数不工作?名称'xxx'未定义

class Window(QtGui.QMainWindow): 

def __init__(self): 
    super(Window, self).__init__() 
    self.setGeometry(500, 150, 500, 600) 
    self.home() 

def home(self): 

    btn_run = QtGui.QPushButton("Run", self) 
    btn_run.clicked.connect(self.run) 
    btn_run.resize(120, 40) 
    btn_run.move(220, 540) 

    self.show() 

def view_splash(arg1): 
    label = QLabel("<font color=red size=10<b>" + n[arg1] + "</b></font>") 
    label.setWindowFlags(Qt.SplashScreen | Qt.WindowStaysOnTopHint) 
    label.show() 
    QtCore.QTimer.singleShot(10000, label.hide) 

def run(self): 
    for i in range(len(lines)): 
     n = random.choice(words) 
     view_splash(0) 
     view_splash(1) 
     time.sleep(600) 

我有一个错误:

view_splash(0) 
NameError: name 'view_splash' is not defined 

我做错了吗? 这应该如何?

+0

好'行'没有被定义为...或'文字'...:/ – Idos

+0

我还没有尝试过这个,但也许'this.view_splash(0)'会工作。 –

+0

你应该修改如何处理Python中的类:https://docs.python.org/3/tutorial/classes.html – idjaw

回答

1

在python中,有必要使用self来访问同一对象的其他方法和属性。当你简单地调用view_splash时,python会查找函数定义,但不会查看Window的方法。通过明确地将view_splash加上self.作为前缀,python就会知道你想要的方法是Window.view_splash,它应该像你期望的那样工作。

因此,对于你的特定代码,这将要求您更新run方法如下所示:

def run(self): 
    for i in range(len(lines)): 
     n = random.choice(words) 
     self.view_splash(0) 
     self.view_splash(1) 
     time.sleep(600) 

我假设有额外的代码外界定义lines和类words作为Window.run然后可以访问的全局变量。