Skip to content
Advertisement

How to get the value of an Entry created in a def?

I’m working on a project and i would like to get the Value of an Entry created in a def (turned on by a button on Tkinter)

So I have my main tkinter menu, with a button which will call the def “panier”. The def “panier” is creating the Entry “value” and another button to call a second def “calcul”. The second def “calcul” will do things with the value of Entry… But then, in the def “calcul”, when i’m trying to do value.get() it tells “NameError: name ‘value’ is not defined”

Here is the code, btw the Entry must be created by the def…

from tkinter import *

def panier():
    value=Entry(test)
    value.pack()
    t2=Button(test,text="Validate",command=calcul)
    t2.pack()

def calcul(value):
    a=value.get()
    #here will be the different calculations I'll do

test=Tk()

t1=Button(test,text="Button",command=panier)
t1.pack()

test.mainloop()

Appreciate every feedback :)

Advertisement

Answer

You can make the variable global like this:

from tkinter import *

def panier():
    global value
    value = Entry(test)
    value.pack()
    t2 = Button(test, text="Validate", command=calcul)
    t2.pack()

def calcul():
    a = value.get()
    print(a)
    #here will be the different calculations I'll do

test = Tk()

t1 = Button(test, text="Button", command=panier)
t1.pack()

test.mainloop()

The global value line makes the variable global so you can use it anywhere in your program.

You can also pass in the variable as an argument like what @JacksonPro suggested t2 = Button(test, text="Validate", command=lambda: calcul(value))

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement