[英]Python error: global declared variable is not declared in the global scope
I am quite new to python, and I tried to make a simple GUI program. 我是python的新手,我试图制作一个简单的GUI程序。 But, I got into a "problem", exactly a warning, that says: 'm' is not defined in the global scope (Python(variable-not-defined-globally)).
但是,我遇到了一个“问题”,一个警告,说:'m'没有在全局范围内定义(Python(变量未定义 - 全局))。
I know that you need to declare a var global inside a function if you want to access it outside that function scope. 我知道如果你想在函数范围之外访问它,你需要在函数内声明一个var global。 Although I don't use this new created variable outside the function, if I don't declare it global, my program only shows the GUI for a fraction of a second, then it closes it.
虽然我不在函数外部使用这个新创建的变量,但是如果我没有将它声明为全局变量,我的程序只会在几分之一秒内显示GUI,然后关闭它。
import sys
from PyQt5.QtWidgets import QApplication, QWidget
def show():
global m
m = QWidget()
m.setWindowTitle("Testing this app")
m.show()
MYAPP = QApplication(sys.argv)
show()
MYAPP.exec_()
Could you explain why is this happening? 你能解释一下为什么会这样吗? Thanks in advance!
提前致谢!
You should also declare m in the global scope before it is used by show(). 在show()使用之前,您还应该在全局范围内声明m。 You can do this by setting
m=None
right before you call show(). 您可以在调用show()之前设置
m=None
来执行此操作。
global
tells python to look for a variable with this name in the global namespace and include it in the local namespace. global
告诉python在全局命名空间中查找具有此名称的变量,并将其包含在本地命名空间中。 This means it must exist in the global namespace first. 这意味着它必须首先存在于全局命名空间中。
import sys
from PyQt5.QtWidgets import QApplication, QWidget
m = None # variable must exist in global namespace first
def show():
global m # this creates a local m that is linked to the global m
m = QWidget()
m.setWindowTitle("Testing this app")
m.show()
MYAPP = QApplication(sys.argv)
show()
MYAPP.exec_()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.