LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Python Global Variable? (http://www.linuxquestions.org/questions/programming-9/python-global-variable-136945/)

ElementNine 01-20-2004 10:27 PM

Python Global Variable?
 
#!/usr/local/bin/python2.3
from Tkinter import *

status = -1

def changeText() :
status = -status
if status == 1 :
mainLabel['text'] = 'Hello World'
if status == -1 :
mainLabel['text'] = ''


mainWindow = Frame()
mainWindow.pack()

mainLabel = Label(mainWindow)
mainLabel['text'] = 'Hello World'
mainLabel.pack()

mainButton = Button(mainWindow)
mainButton['text'] = 'On/Off'
mainButton['command'] = changeText()
mainButton.pack()

mainWindow.mainloop()


Im trying to learn python, in that script i get an error cuz im trying to access status from changeText how do i make status a global variable to that the script will work?

rshaw 01-20-2004 11:21 PM

to access variables outside the local namespace you need to use the "global" keyword as in:

status = -1

def changetext():
global status
status = -status

if status ==1:
do_stuff
else:
do_other_stuff

ElementNine 01-20-2004 11:27 PM

Well cool that got rid of the errors. but the text doesnt change, is it not possible to modify labels after they have been set ? Guess i should continue reading the book and see if it mentions anything. Thanks though that global keyword helped with alot of other scripts im trying out

jimscafe 01-21-2004 03:13 AM

I think you need to use the configure method like this

mainLabel.configure(text='New Text')

Strike 01-21-2004 07:22 AM

Quote:

Originally posted by rshaw
to access variables outside the local namespace you need to use the "global" keyword as in:

status = -1

def changetext():
global status
status = -status

if status ==1:
do_stuff
else:
do_other_stuff

Actually, you only need to use the global keyword if you want to CHANGE variables outside the local namespace and you want those changes to stick. Observe:
Code:

>>> foo = 1
>>> def bar():
...    print foo
...
>>> bar()
1
>>> def changefoo():
...    foo = 2
...    print foo
...
>>> changefoo()
2
>>> foo
1
>>> def reallychangefoo():
...    global foo
...    foo = 2
...    print foo
...
>>> reallychangefoo()
2
>>> foo
2
>>>

All functions inherit the set variables of their callers, but only copies of them, not references to them. So if you modify one, it doesn't modify the variable in the caller namespace, just the local namespace ... unless you use global.

PerryTachett 11-05-2007 12:53 PM

But what about classes?
I have a class, and I want it to get the global variables. How do I do this?

This doesn't seem to work:

Code:

class MyClass:
    global foo, bar



All times are GMT -5. The time now is 07:50 PM.