[Tkinter-discuss] Tkinter variable sharing from function to function

Michael Lange klappnase at web.de
Sun Mar 4 13:42:42 CET 2012


Hi,

Thus spoketh "ed(LV)" <ambed at inbox.lv> 
unto us on Sat, 3 Mar 2012 23:38:17 -0800 (PST):

> *Hello!
> Im beginner at Tkinter and this is my 1st project.
> I want make programm that calculate resistor value from colors, but i
> can`t get variables out of functions.
> Here you can see all code:*
> 
(...)
> *The main problem is that I can`t read variables x, x1, x2 on button
> "CALCULATE" press.
> Thank you for support!*

when I run you code I get each time I press The "Calculate" button the
error message:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1413, in __call__
    return self.func(*args)
  File "test7.py", line 326, in funf
    z=(x+x1)*x2
NameError: global name 'x' is not defined

which shows clearly what happens:
the callback

def funf():
    z=(x+x1)*x2
    w.itemconfig(t6,text=z)

tries to use a variable "x" which is not defined in the function's
namespace, which covers basically everything that is defined *globally*
plus anything defined within the function's *local* namespace, which
means in the body of the function itself.

I set up a minimal example to illustrate the difference between a local
and a global variable, I hope you see the point:

########### file test.py ###################
from Tkinter import *

root = Tk()
x = 1

def func1():
    x = 0
    print 'value of x:', x

def func2():
    global x
    print 'value of x:', x

def func3():
    global x
    x += 2
    print 'value of x:', x


Button(text='Func 1', command=func1).pack()
Button(text='Func 2', command=func2).pack()
Button(text='Func 3', command=func3).pack()

root.mainloop()
###########################################

So possible solutions for your problem might be:

* declare global variables in your functions ( I haven't properly
investigated all of your code, but I guess you would probably have to
declare globals in all of your button callbacks, which is most often
considered to be bad practice, although it will work without problems if
it is done carefully), or
* use Tkinter variables , as it seems was one of your first tries. Then
you can simply call something like var1.set(1) from within the function
body.

If you want to learn more about namespaces in Python and how they work, a
good starting point is:

http://www.freenetpages.co.uk/hp/alan.gauld/tutname.htm

I hope this helps

Michael


.-.. .. ...- .   .-.. --- -. --.   .- -. -..   .--. .-. --- ... .--. . .-.

One of the advantages of being a captain is being able to ask for
advice without necessarily having to take it.
		-- Kirk, "Dagger of the Mind", stardate 2715.2


More information about the Tkinter-discuss mailing list