Confusion with python global variables, pygame event
I read a couple more questions on this topic, but I don't seem to need working python variables.
I have three files: main.py, menu.py and game.py.
menu.py contains a menu function that is mostly executed; main has a "running" variable for its main loop, and I want functions in other files to be able to set the value to 0 to quit the game.
But I cannot get it to work; for example if I do this:
menu.py
...
class gameMenu():
def __init__(self, screen, background):
#self.event = event
global running
...
running = 0
main.py
...
from menu import *
...
global running
running = 1
title = gameMenu(screen, background)
title.run()
...
print running
But the main thing will always print 1. How can I get a menu to change the current variable in main?
Also, in the menu loop, I have this function:
for e in pygame.event.get():
if e.type == pygame.QUIT:
print 'Close!'
self.isRunning = 0
running = 0
if e.type == pygame.JOYBUTTONDOWN:
print 'Button Down!'
self.isRunning = 0
This code works fine in another program, but in this one the second if never gets executed, and honestly I don't understand why.
If you want the complete code, it's here: http://dumptext.com/KuwcaWpH
Thank you for your help.
source to share
In your code, you are not importing a global variable running
from main.py
to menu.py
. When you do -
if e.type == pygame.QUIT:
print 'Close!'
self.isRunning = 0
running = 0
You just set the local name (variable) to 0, it doesn't affect the variable running
in main.py
. You might want to add the following line at the beginning of the function -def run(self):
def run(self):
global running
self.isRunning = 1
It also seems that you are defining running = 1
in main.py
, it might be a shadow global variable running
that you want to import from menu.py
. Try to remove this line. Or would it be best to do -
import menu
Then access the global variable as - menu.running
source to share
Global
variables in Python are actually only within the same file. The keyword is used to allow local scopes (like functions and loops) to assign values ββto broader cloud variables.
When going from file to file, the import is what you actually want to use. Importing allows you to see variables from another script, not just functions and objects. It also allows you to assign them. While these assignments will not affect the script how it is saved to disk, it can change values ββsuch as running
.
So you could do
from menu import running
And then check and assign its value. Or, if you've just used it import menu
, refer to running
using menu.running
.
source to share