名称 'xxx' 未定义 [英] Name 'xxx' is not defined
问题描述
为什么这两个函数不行?
类窗口(QtGui.QMainWindow):def __init__(self):super(Window, self).__init__()self.setGeometry(500, 150, 500, 600)self.home()定义家(自己):btn_run = QtGui.QPushButton("Run", self)btn_run.clicked.connect(self.run)btn_run.resize(120, 40)btn_run.move(220, 540)自我展示()def view_splash(arg1):label = QLabel("" + n[arg1] + "")label.setWindowFlags(Qt.SplashScreen | Qt.WindowStaysOnTopHint)标签.show()QtCore.QTimer.singleShot(10000, label.hide)定义运行(自我):对于 i 在范围内(len(行)):n = random.choice(words)view_splash(0)view_splash(1)时间.睡眠(600)
我有那个错误:
view_splash(0)NameError:未定义名称view_splash"
我做错了什么?这应该是什么样子?
在python中,需要使用self
来访问同一对象的其他方法和属性.当您简单地调用view_splash
时,python 会查找函数定义,但不会查看Window
的方法.通过显式地在 view_splash
前面加上 self.
前缀,python 就知道你想要方法 Window.view_splash
并且它应该像你期望的那样工作.>
因此,对于您的特定代码,这需要您将 run
方法更新为以下内容:
def run(self):对于 i 在范围内(len(行)):n = random.choice(words)self.view_splash(0)self.view_splash(1)时间.睡眠(600)
我假设在类的外部还有额外的代码,它定义了lines
和words
作为全局变量,Window.run
然后就可以访问了.
Why these two function want not work ?
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)
I have that error:
view_splash(0)
NameError: name 'view_splash' is not defined
What I'm doing wrong ? How this should look like ?
In python, it is necessary to use self
to access other methods and attributes of the same object. When you simply call view_splash
, python looks for the function definition but will not look at the methods of Window
. By explicitly prefixing view_splash
with self.
, python then knows that you want the method Window.view_splash
and it should work as you expect.
So for your specific code, this would require you to update your run
method to be the following:
def run(self):
for i in range(len(lines)):
n = random.choice(words)
self.view_splash(0)
self.view_splash(1)
time.sleep(600)
I'm assuming that there is additional code outside of the class which defines lines
and words
as global variables which Window.run
can then access.
这篇关于名称 'xxx' 未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!