Python Forum

Full Version: How can I access this variable from a def?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey, I'm new here and pretty new to programming as well.

I'm trying to make a simple text entry box that prints the text upon pressing return. However, I'm finding it impossible to reference the variable from outside the function.

I can declare global variable e to get around it, but I was told globals are bad. Is there a better way to do this sort of thing?

This is as far as I can get.

[inline]from tkinter import *

root = Tk()

def places():
title = Label(root, text="Where do you want to go?").grid(row=0)
e = Entry()
e.grid(row=1)
e.focus_set()
e.bind("<Return>", key)

def key(event):
print(e.get)


places()
root.mainloop()
[/inline]

returns NameError: name 'e' is not defined on pressing enter.
To get a value out of a function, you return it. Then you can either print it directly, or assign it to a variable and print it later:

def add2(x):
    return x + 2
print(add2(3))
eight = add2(6)
print(eight)