KyleR-
KyleR-

Reputation: 33

Accessing a variable with .get() inside a function Python/Tkinter 3.4

For my software major I'm creating a budgeting program and I'm currently stuck on a section with a function. I have an entry box and button defined as:

incomeEntry = Entry(width=15)
testButton = Button(text="Save", command=Save)

And my Save function is:

def Save():
   a = incomeEntry.get()
   return(a)

a = Save()
print(a)

So what I'm trying to do is get the input from incomeEntry, and then return it outside the function so I can use it for later calculations. If I change a = 3 it returns 3, but it doesn't work with the .get() function.

Could anyone help?

Upvotes: 0

Views: 1080

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385830

The best solution, IMO, is to use object oriented techniques to develop your program. You can then use object attributes to save values.

For example, the following shows how to call a function named Save via a button, and then another button will print what was saved via a Print button.

class Example(object):
    def __init__(self, ...):
        ...
        self.savedValue = None
        self.saveButton = tk.Button(..., command=self.Save)
        self.printButton = tk.Button(..., command=self.Print)
        ...

    def Save(self):
        ...
        self.savedValue = "whatever"
        ...

    def Print(self):
        ...
        print("last saved value: " + self.savedValue)
        ...

Upvotes: 1

Related Questions