Steele Farnsworth
Steele Farnsworth

Reputation: 893

How do you use tkinter to display the output of a function call?

I'm trying to use using tkinter to demonstrate the functionality of a given python library. The GUI must take textual input from the user, await a button push, send the input to the function, display the result, and repeat this process every time the user pushes the button.

import tkinter as tk


def do_something(phrase):
    return phrase + phrase


def main():
    root = tk.Tk()
    root.title("Demo")

    tk.Label(root, text="Please enter a sentence: ").grid(row=0)
    user_input = tk.Entry(root)
    user_input.grid(row=0, column=1)
    result = tk.Button(root, text='Do something', command=do_something(user_input.get())).grid(row=1, column=1, sticky=tk.W, pady=4)
    tk.Label(root, text=result).grid(row=2, column=1)

    root.mainloop()


if __name__ == "__main__":
    main()

I don't know how to access the value returned by do_something(). I imagine that once I understand how to do that, there might be the issue of ensuring that the process can be repeated as many times as the window remains open and the user presses the button.

Upvotes: 2

Views: 3711

Answers (1)

acw1668
acw1668

Reputation: 46687

Guess that you want to set the text of the last label based on the input value of user_input. You can do it as below:

import tkinter as tk

def do_something(phrase):
    return phrase + phrase

def main():
    root = tk.Tk()
    root.title("Demo")

    tk.Label(root, text="Please enter a sentence: ").grid(row=0)
    user_input = tk.Entry(root)
    user_input.grid(row=0, column=1)
    result = tk.Label(root, text='')
    result.grid(row=2, column=0, columnspan=2)
    btn = tk.Button(root, text='Do something')
    btn.config(command=lambda: result.config(text=do_something(user_input.get())))
    btn.grid(row=1, column=1, sticky=tk.W, pady=4)

    root.mainloop()

if __name__ == "__main__":
    main()

Upvotes: 2

Related Questions