1

I have a function that has a tkinter window defined and run inside of it. There is a button in that window, and I need the button to execute a return statement and return a value for the function.

The way to do things other than run argumentless functions from button callbacks seems to be lambda, but I can't figure out a way to do this with lambda, as any value returned from the lambda registers as the return value for the lambda.

The gist of my code is like this:

from tkinter import *

def function():
    root = Tk()

    entry = Entry(root)
    entry.pack()

    button = Button(root, text = "I'm a button", command = return entry.get()) #Does not work, you can't do this in a callback
    button.pack()

    root.mainloop()

What I'm trying to figure out is how to rewrite that return statement so that it is valid for the command argument.

1
  • 2
    return is useless with Button because there is nobody who can receive returned value. Commented Dec 13, 2015 at 20:24

2 Answers 2

1

You can't really do that. The best way to do it is with a function but I'm not sure why you would want to do that. It seems a bit odd... 😉 As commented, the a Tkinter script runs differently to a normal Python script so nothing will be able to use the returned value. Store it as a variable if you need it.

I would just create a function that stores it as a variable.

def foo():
    gah=entry.get()
    # return entry.get()
    # stuff or no stuff

button=Button(root, text="ghost", command=foo)
Sign up to request clarification or add additional context in comments.

2 Comments

But it would be a local variable. Finally, I just use global for this (and ignore the feeling of sleaziness for using them :^| )
This serves no purpose because the local variable is immediately discarded when the function returns. Declaring gah a global might work as long as foo is defined in the same module with the code that references the global variable).
0

Long story short: How do I pass a variable by reference?

Example of a mutable object that persists after the callback

import tkinter as tk
from tkinter import messagebox

def function():
    root = tk.Tk()
    returned_values = {} 

    entry = tk.Entry(root)
    entry.pack()
    
    button = tk.Button(root, text = "I'm a button", command=lambda: callback(entry.get(), returned_values))
    button.pack()

    root.mainloop()
    
def callback(info, returned_values):
    returned_values[len(returned_values)+1] = info
    messagebox.showinfo('Success', f"Mutable: {returned_values}")
   
function()

As you can see, returned_values persists because it is a mutable object

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.