python tkinter return value from function used in command

how do i get the return value A to C? I am not using class by the way.

def button:
    mylabel = Label(myGui, text = "hi").grid(row = 0, column = 0)
    A = B.get()
    return A

B = StringVar()
C = ""
myentry = Entry(myGui, textvariable = B).grid(row = 1, column = 0)
Submit = Button(myGui, text = "Submit", command = button).grid(row = 1, column = 1)

Solution 1:

Short answer: you cannot. Callbacks can't return anything because there's nowhere to return it to -- except the event loop, which doesn't do anything with return values.

In an event based application, what you typically will do is set an attribute on a class. Or, if you're a beginner, you can set a global variable. Using a global variable isn't a good idea for real code that has to be maintained over time but it's OK for experimentation.

So, for example, since C appears to be a global variable in your example, you would do something like:

def button():
    global C
    mylabel = Label(myGui, text = "hi").grid(row = 0, column = 0)
    A = B.get()
    C = A

Solution 2:

You could call C.set from within the button function:

def button:
    mylabel = Label(myGui, text = "hi").grid(row = 0, column = 0)
    A = B.get()
    C.set(A)
    # return A   # return values are useless here

Solution 3:

Old question, but most answers suggested a global variable. I don't like using too many global variables in my projects, so here's my solution.

When declaring your Tkinter button, you can use a lambda function as the command. This lambda can interact with variables that are within the same namespace as the button you are defining. Be sure to define this variable before initializing the button.

def button():
    mylabel = Label(myGui, text = "hi").grid(row = 0, column = 0)
    A = B.get()
    return A

B = StringVar()
C = ""
myentry = Entry(myGui, textvariable = B).grid(row = 1, column = 0)
Submit = Button(myGui, text = "Submit", command = lambda: C=button()).grid(row = 1, column = 1)

You may need to have self as an argument for button depending on your project organization, but the concept is the same. Lambda commands are also useful for passing arguments to the button command.

Solution 4:

it's easy just declare A a global.

def button:
global A
mylabel = Label(myGui, text = "hi").grid(row = 0, column = 0)
A = B.get()
return A

B = StringVar()`
C = ""
myentry = Entry(myGui, textvariable = B).grid(row = 1, column = 0)
Submit = Button(myGui, text = "Submit", command = button).grid(row = 1, column = 1)
# and then A is not empty
B= A

Solution 5:

You create a child class of Tkinter.Tk, and define a member variable self.A in that class. Then you can mimic return behavior by

self.A = B.get()

See, Return values of Tkinter text entry, close GUI