Python Forum

Full Version: tkinter issue with variables carrying over between functions
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I suspect this is a very simple issue... I am trying to use a variable, loaded in one operation, within another operation. It is telling me the variable doesn't exist.

Below is the simplest way to reproduce my issue.

from tkinter import *

root = Tk()
root.title('Temp')
root.geometry('300x300')

def Import():
    u = 1
    v = 2

directoryButton = Button(root, text='Import', command=Import, padx=15)
directoryButton.grid(row=0,column=0 )

def Calc():
    t = u*v
    print(t)

directoryButton = Button(root, text='Calc', command=Calc, padx=15)
directoryButton.grid(row=0,column=1 )

root.mainloop()
Help would be massively appreciated.

Thanks,
You could do something like this:
from tkinter import *
 
root = Tk()
root.title('Temp')
root.geometry('300x300')
u = 0
v = 0

def Import():
    global u, v
    u = 1
    v = 2
 
directoryButton = Button(root, text='Import', command=Import, padx=15)
directoryButton.grid(row=0,column=0 )
 
def Calc():
    t = u*v
    print(t)
 
directoryButton = Button(root, text='Calc', command=Calc, padx=15)
directoryButton.grid(row=0,column=1 )
 
root.mainloop()
For fun comment out the "global x, y" line and run the program. Notice any changes?

Functions can see variables from their enclosed scope (meaning Import and Calc can see the x and y that are assigned at the top of the module). However, when you don't tell Calc to use the global x, y it chooses to create new variables inside the function that just happen to have the same name.

global is fine to use for short programs, but as programs get bigger it becomes difficult keeping track of what is a local and what is a global variable. If you have multiple variables that are manipulated by multiple functions sometimes it makes sense to create a class that encapsulates the data and the functions.
class Example:
    def __init__(self, u=0, v=0):
        self.u = u
        self.v = v

    def Import(self, u, v):
        self.u = u
        self.v = v

    def Calc(self):
        return self.u * self.v

obj = Example(1, 2)
print(obj.calc())
This is too simple an example, but if you have a lot of operations that can be performed on your data a class may be a good choice.