Python错误: global declared variable is not declared in the global scope

标签 python variables global-variables

我对 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/

相关文章:

python - 为什么 pandas str.replace 返回 NaN?

javascript - 设置变量,而不是让最终用户从 html 表单输入变量

batch-file - 批处理文件 - 目录的结果分离

C: 函数可以返回一个全局变量吗?

php - 如何使用 $_SERVER 变量的路径,修改它并将其分配给 PHP 中的某个变量?

python - pandas 日期时间转换不一致

php - 什么是 PHP 相当于 Python 的 Try : . .. 除了:

python - 将数据框中的列转换为 "classes"?

java - 'int' 和 'Integer' 类型之间的区别

JavaScript 命名空间全局变量与全局属性