我对 python 很陌生,我尝试制作一个简单的 GUI 程序。 但是,我遇到了一个“问题”,确切地说是一个警告,上面写着: “m”未在全局范围内定义(Python(变量未定义全局))。
我知道如果你想在函数作用域之外访问它,你需要在函数内声明一个 var 全局变量。虽然我不在函数外部使用这个新创建的变量,但如果我不将其声明为全局变量,我的程序只会显示 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_()
您能解释一下为什么会发生这种情况吗?提前致谢!
最佳答案
global
告诉 python 在全局命名空间中查找具有该名称的变量,并将其包含在本地命名空间中。这意味着它必须首先存在于全局命名空间中。
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_()
关于Python错误: global declared variable is not declared in the global scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55765372/