Python Forum
How can I access this variable from a def?
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I access this variable from a def?
#1
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.
Reply
#2
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)
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Cant access variable from anywhere Frankduc 33 4,345 Nov-09-2022, 03:33 PM
Last Post: deanhystad
  Can we access instance variable of parent class in child class using inheritance akdube 3 13,887 Nov-13-2020, 03:43 AM
Last Post: SalsaBeanDip
  Access a variable of a daemon peek_no_boo 8 3,299 Apr-03-2020, 07:29 PM
Last Post: BrendanD
  How to access class variable? instances vs class drSlump 5 3,285 Dec-11-2019, 06:26 PM
Last Post: Gribouillis
  Can access class private variable? Michael 2 7,145 Aug-11-2017, 01:59 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020