Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. But, I got into a "problem", exactly a warning, that says: 'm' is not defined in the global scope (Python(variable-not-defined-globally)).

I know that you need to declare a var global inside a function if you want to access it outside that function scope. 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.

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!

like image 927
Andrew T Avatar asked Apr 19 '19 17:04

Andrew T


1 Answers

global tells python to look for a variable with this name in the global namespace and include it in the local namespace. 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_()
like image 136
Tom Lubenow Avatar answered Nov 14 '22 21:11

Tom Lubenow