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
Answer from Bryan Oakley on Stack Overflow
๐ŸŒ
Quora
quora.com โ€บ How-can-you-return-a-value-from-a-function-that-is-executed-from-the-Tkinter-button-Python-TkInter-development
How to return a value from a function that is executed from the Tkinter button (Python, TkInter, development) - Quora
Most commonly, what you want to ... your value by calling its set method. (That member might be directly connected to a widget by Tk, or it might be something you manually call get on elsewhere in your code.) Something like this: ... How do you run Tkinter function with both a key bind and a button command (Python, function, tkinter, development)? How do you update label text in Python Tkinter (Python, TkInter, development)? RelatedHow do you return a function ...
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-24463.html
Returning a value from a tkinter.button call
I am trying to code without using globals. I am using the tkinter.button (see below) to enter some numbers into a variable. Ideally I want the tkinter.button call to return the number entered so that I don't have to make use of the global. Anyone a...
๐ŸŒ
Reddit
reddit.com โ€บ r/python โ€บ using tkinter after and get a return value
r/Python on Reddit: Using Tkinter After And Get A Return Value
November 28, 2019 -

Im making this app that need to delay before call a function and get the return value. but because of time.sleep is freezing tkinter gui so i used tkinter.after. tkinter.after is working and diddnt frezee the window, but i cannot get a return value of a function that i've called. because after i delayed and get the returned value, i've to return it again to the other function that called this function.

i've been struggling with this, please if any of u know any solutions, help me

this is the basic example of whats going on

import tkinter as tk
from time import sleep


def getvalue():

    value = "haha"

    sleep(3)

    return value


def printvalue():

    value = getvalue()

    print(value)



app = tk.Tk()
app.geometry("500x300")

button = tk.Button(app, text="print value", command=printvalue)
button.pack()

app.mainloop()
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to return variables from tkinter windows?
r/learnpython on Reddit: How to return variables from Tkinter windows?
January 7, 2024 -

Say I have a function ask_for_number() which is called when a button is pressed. It creates a Toplevel window with a label that says 'Enter a number', an Entry widget, and a button that says 'Validate' which calls a function called validate_entry. validate_entry checks if a number is entered, using

try:
    int(entry.get())
except TypeError:
    # handle the error

but because this is a different function the only way to access entry that I know of is to make it global first. I can't use 'return entry' and re-use the variable in validate_entry, because return doesn't work within tkinter mainloop (callbacks don't and can't return anything). What is the 'proper' way to do it without using globals?

Top answer
1 of 4
4
Method 1: use an instance variable in the toplevel class. Requires that the popup is "modal" (disables the main window). import tkinter as tk class Main(tk.Frame): def __init__(self, master=None, **kwargs): super().__init__(master, **kwargs) lbl = tk.Label(self, text="this is the main frame\n") lbl.pack() btn = tk.Button(self, text='click me', command=self.open_popup) btn.pack() self.output = tk.Label(self) self.output.pack() def open_popup(self): print("runs before the popup") p = Popup(self) print("runs after the popup closes") self.output.config(text=f"Got data returned:\n {p.result!r}") class Popup(tk.Toplevel): """modal window requires a master""" def __init__(self, master, **kwargs): super().__init__(master, **kwargs) lbl = tk.Label(self, text="this is the modal window popup\ntype something") lbl.pack() self.ent = tk.Entry(self) self.ent.insert(0, "Hello world") self.ent.pack() btn = tk.Button(self, text="OK", command=self.on_ok) btn.pack() # The following commands keep the popup on top. # Remove these if you want a program with 2 responding windows. # These commands must be at the end of __init__ self.transient(master) # set to be on top of the main window self.grab_set() # hijack all commands from the master (clicks on the main window are ignored) master.wait_window(self) # pause anything on the main window until this one closes def on_ok(self): self.result = self.ent.get() # save the return value to an instance variable. self.destroy() def main(): root = tk.Tk() window = Main(root) window.pack() root.mainloop() if __name__ == '__main__': main() Method 2: Send a callback from the main code to the toplevel window: import tkinter as tk class Main(tk.Frame): def __init__(self, master=None, **kwargs): super().__init__(master, **kwargs) lbl = tk.Label(self, text="this is the main frame\n") lbl.pack() btn = tk.Button(self, text='click me', command=self.open_popup) btn.pack() self.output = tk.Label(self) self.output.pack() def open_popup(self): Popup(self, self.update_main) # send the method that should be called at the end def update_main(self, result): self.output.config(text=f"Got data returned:\n {result!r}") class Popup(tk.Toplevel): def __init__(self, master, callback, **kwargs): super().__init__(master, **kwargs) self.callback = callback lbl = tk.Label(self, text="this is the modal window popup\ntype something") lbl.pack() self.ent = tk.Entry(self) self.ent.insert(0, "Hello world") self.ent.pack() btn = tk.Button(self, text="OK", command=self.on_ok) btn.pack() def on_ok(self): self.callback(self.ent.get()) # send the back to the other class. self.destroy() def main(): root = tk.Tk() window = Main(root) window.pack() root.mainloop() if __name__ == '__main__': main() Method 3: pass along a tkinter variable and just have all places that need it linked. Immediate updates if used as a textvariable. import tkinter as tk class Main(tk.Frame): def __init__(self, master=None, **kwargs): super().__init__(master, **kwargs) lbl = tk.Label(self, text="this is the main frame\n") lbl.pack() btn = tk.Button(self, text='click me', command=self.open_popup) btn.pack() self.txtvar = tk.StringVar(value="Hello World") self.output = tk.Label(self, textvariable=self.txtvar) self.output.pack() def open_popup(self): Popup(self, self.txtvar) class Popup(tk.Toplevel): def __init__(self, master, txtvar, **kwargs): super().__init__(master, **kwargs) lbl = tk.Label(self, text="this is the modal window popup\ntype something") lbl.pack() self.ent = tk.Entry(self, textvariable=txtvar) # could also use txtvar.set() in the ok method. self.ent.pack() btn = tk.Button(self, text="OK", command=self.destroy) btn.pack() def main(): root = tk.Tk() window = Main(root) window.pack() root.mainloop() if __name__ == '__main__': main() Method 4: use a tkinter Event to signal when things should happen. I used a global data structure here but you could also pass a mutable around instead. import tkinter as tk data_structure = "" # any kind of data structure class Main(tk.Frame): def __init__(self, master=None, **kwargs): super().__init__(master, **kwargs) lbl = tk.Label(self, text="this is the main frame\n") lbl.pack() btn = tk.Button(self, text='click me', command=self.open_popup) btn.pack() self.output = tk.Label(self) self.output.pack() master.bind("<>", self.update_main) def open_popup(self): Popup(self, self.update_main) def update_main(self, event=None): self.output.config(text=f"Got data returned:\n {data_structure!r}") class Popup(tk.Toplevel): def __init__(self, master, callback, **kwargs): super().__init__(master, **kwargs) self.callback = callback lbl = tk.Label(self, text="this is the modal window popup\ntype something") lbl.pack() self.ent = tk.Entry(self) self.ent.insert(0, "Hello world") self.ent.pack() btn = tk.Button(self, text="OK", command=self.on_ok) btn.pack() def on_ok(self): global data_structure data_structure = self.ent.get() # save the data. self.master.event_generate("<>") # trigger actions elsewhere self.destroy() def main(): root = tk.Tk() window = Main(root) window.pack() root.mainloop() if __name__ == '__main__': main() method 5: Similar to event based, use a loop to wait for new data. Allows new data to come from many places. Again could use global data structure, but for contrast will use mutable instance variable: import tkinter as tk from queue import Queue class Main(tk.Frame): def __init__(self, master=None, **kwargs): super().__init__(master, **kwargs) self.data_structure = Queue() lbl = tk.Label(self, text="this is the main frame\n") lbl.pack() btn = tk.Button(self, text='click me', command=self.open_popup) btn.pack() self.output = tk.Label(self) self.output.pack() self.event_monitor() # start the loop to monitor for new data def open_popup(self): Popup(self) def event_monitor(self): if not self.data_structure.empty(): result = self.data_structure.get() self.output.config(text=f"Got data returned:\n {result!r}") self.after(100, self.event_monitor) class Popup(tk.Toplevel): """modal window requires a master""" def __init__(self, master, **kwargs): super().__init__(master, **kwargs) lbl = tk.Label(self, text="this is the modal window popup\ntype something") lbl.pack() self.ent = tk.Entry(self) self.ent.insert(0, "Hello world") self.ent.pack() btn = tk.Button(self, text="OK", command=self.on_ok) btn.pack() def on_ok(self): self.master.data_structure.put(self.ent.get()) # send the data to the queue self.destroy() def main(): root = tk.Tk() window = Main(root) window.pack() root.mainloop() if __name__ == '__main__': main() Method 6: trace a variable: import tkinter as tk class Main(tk.Frame): def __init__(self, master=None, **kwargs): super().__init__(master, **kwargs) lbl = tk.Label(self, text="this is the main frame\n") lbl.pack() btn = tk.Button(self, text='click me', command=self.open_popup) btn.pack() self.txtvar = tk.StringVar(value="Hello World") self.txtvar.trace_add("write", self.update_main) self.output = tk.Label(self) self.output.pack() def open_popup(self): print("runs before the popup") Popup(self, self.txtvar) print("runs after the popup closes") def update_main(self, *event): self.output.config(text=f"Got data returned:\n {self.txtvar.get()!r}") class Popup(tk.Toplevel): def __init__(self, master, txtvar, **kwargs): super().__init__(master, **kwargs) lbl = tk.Label(self, text="this is the modal window popup\ntype something") lbl.pack() self.ent = tk.Entry(self, textvariable=txtvar) # or use txtvar.set() from the ok button callback self.ent.pack() btn = tk.Button(self, text="OK", command=self.destroy) btn.pack() def main(): root = tk.Tk() window = Main(root) window.pack() root.mainloop() if __name__ == '__main__': main() etc, etc. Many ways to do this.
2 of 4
2
In short, classes. Busy now, but I can give an example later.
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Returning a value from a tkinter popup - Python Help - Discussions on Python.org
April 12, 2022 - I need to ask the user for an arbitrarily long list of key-folder pairs, so I use Toplevel to create a popup where i lay out a growable list pairs of custom buttons (one to bind the key and one to select the folder). Iโ€™d then like to wait til the user closes the window and read the status on the widgets, but wait_window() waits until itโ€™s too late and the widgets are already deconstructed Is there an easy way to do something like popup.wait_window() and access the attributes in the widgets?
๐ŸŒ
Gitbooks
forgoal.gitbooks.io โ€บ python โ€บ content โ€บ creating-a-tkinter-class-and-waiting-for-a-return-value.html
Creating a Tkinter class and waiting for a return value ยท Python
import Tkinter as tk class MyDialog(object): def __init__(self, parent): self.toplevel = tk.Toplevel(parent) self.var = tk.StringVar() label = tk.Label(self.toplevel, text="Pick something:") om = tk.OptionMenu(self.toplevel, self.var, "one", "two","three") button = tk.Button(self.toplevel, text="OK", command=self.toplevel.destroy) label.pack(side="top", fill="x") om.pack(side="top", fill="x") button.pack() def show(self): self.toplevel.deiconify() self.toplevel.wait_window() value = self.var.get() return value class Example(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent)
๐ŸŒ
Python
python-list.python.narkive.com โ€บ oKfJuiPk โ€บ returning-values-from-a-lambda
Returning values from a lambda
For example, def operations(a,b): return a+b, a*b from Tkinter import * root = Tk() btn = Button(root, text='Press Me', command=lambda a=2, b=5: operations(a,b)) btn.pack() How do I assign the returned values to variables, say x,y ? I guess I want to do something like, lambda a=2, b=5: x,y=operations(a,b) but this gives me the error: SyntaxError: can't assign to lambda Is this possible ?
Find elsewhere
๐ŸŒ
Google APIs
storage.googleapis.com โ€บ dbalarwbwgfxme โ€บ tkinter-button-command-with-return-value.html
Tkinter Button Command With Return Value at Nathan Fulton blog
July 23, 2024 - First, you need to make your variable of a tkinter string type like this: ... The only known way to get the return value of a button command is by using button.invoke(). The entry widget has a get() method to get the value entered by the user.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-get-the-value-of-a-button-in-the-entry-widget-using-tkinter
How to get the value of a button in the Entry widget using Tkinter?
To update the Entry widget, we can delete the previous value using delete(0, END) method. # Import the required libraries from tkinter import * from tkinter import ttk # Create an instance of tkinter frame or window win=Tk() # Set the size of the window win.geometry("700x350") def on_click(text): entry.delete(0, END) entry.insert(0,text) # Add an Entry widget entry=Entry(win, width= 25) entry.pack() # Add Buttons in the window b1=ttk.Button(win, text= "A", command=lambda:on_click("A")) b1.pack() b2=ttk.Button(win, text= "B", command=lambda: on_click("B")) b2.pack() b3=ttk.Button(win, text= "C", command=lambda: on_click("C")) b3.pack() win.mainloop()
Top answer
1 of 3
2

The whole point of attaching a command to a button is to implement the answer to the question "what do I want to happen when I click the button?". In your case, the answer is "I want it to a) get the value from an entry widget, b) calculate a new value, and c) append it to a list".

So, write a function that does that, and then call that function from your button. In this case you don't need lambda since you have a 1:1 relationship between the button and entry widget. There's nothing wrong with lambda per se, but in this case it adds complexity without providing any value so I recommend not using it. By not using lambda, the code will be easier to debug and maintain over time since it's hard to set breakpoints or add additional functionality inside a lambda.

For example:

def f(x):
    y=x**2
    z=x-1

def do_calculation():
    x_value = float(x.get())
    result = f(x_value)
    my_list.append(result)

...
tk.Button(..., command=do_calculation)
2 of 3
1

Use append(f(x)) in lambda and return [y,z] in f(x). And you have to convert string from Entry into int or float.

import tkinter as tk

# --- functions ---

def f(x):
    x = int(x.get()) # convert string to int (or float)
    y = x**2
    z = x-1
    return [y, z]

# --- main ---

my_list = []

master = tk.Tk()

e = tk.Entry(master)
e.pack()

cmd = lambda x=e:my_list.append(f(x))

tk.Button(master, text="Ok", command=cmd).pack()

master.mainloop()

print(my_list)

You can convert x in lambda and then f(x) could do only math calculations

EDIT: corrected version as @TadhgMcDonald-Jensen noted in the comment.

def f(x):
    return [x**2, x-1]

#cmd = lambda x=int(e.get()):my_list.append(f(x)) # wrong version
cmd = lambda:my_list.append(f(int(e.get()))) # correect version
๐ŸŒ
Sololearn
sololearn.com โ€บ en โ€บ Discuss โ€บ 211158 โ€บ tkinter-how-do-i-show-a-value-of-a-code-to-the-user-after-he-presses-a-button
Tkinter. How do i show a value of a code to the user after he presses a button??? | Sololearn: Learn to code for FREE!
February 11, 2017 - i did a code to do some mat calculation . the user enters 2 values and then he presses button . the code will take that 2 values do some math and return a result . how do i show that result to the user ? ... When creating your tk.Button() object pass in command=func_name and in that function update your labels text. Or in the button.config() from tkinter import * bye = 'Goodbye' def update_text(): label.config(text=bye) root = Tk() root.title("My Title") label = Label(root, text="Hello") label.pack() button = Button(root, text="Click Me", width=30, command=update_text) button.pack() root.mainloop()
๐ŸŒ
CopyProgramming
copyprogramming.com โ€บ howto โ€บ tkinter-button-command-return-value
Python: Is it possible to obtain a return value from the command of a Tkinter Button?
April 1, 2023 - There are two ways to do it: 1) a global variable 2) to store the variable you want to return in another class: 1) define the function you use in a button: def yourFunction (x): global variab variab = x. Transfer the function to your button: button = Button (root, command=lambda: yourFunction (x)) ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ getting the return value of a lambda function called from tkinter button
r/learnpython on Reddit: Getting the return value of a lambda function called from tkinter button
May 12, 2018 -

Alright, so I am creating a small GUI program using tkinter, and one of the functions it performs requires a user to enter a document number. It then makes changes to the database based on the number entered, so I want to make sure the user entered it correctly.

To accomplish this, I am asking the user to enter the number again in a pop up window and then I compare the values and return True if they match or False otherwise.

I am having a hard time getting my def: to return the result of the lambda function inside of it.

I've tried assigning the lambda expression to a variable, but that seems to not return True or False as expected, but rather some internal Python stuff (memory addresses and such).

Am I trying to do this the right way? Is there a simpler way?

My code

๐ŸŒ
Tcl Wiki
wiki.tcl-lang.org โ€บ page โ€บ tkinter.Button
tkinter.Button
When a user invokes the button (by pressing mouse button 1 with the cursor over the button), then the Python callback specified in the command option is invoked. The following commands are possible for button widgets: instance.cget("option") Returns the current value of the configuration option ...