0

How can I access a variable that contains the user input from a tkinter entry box? I want to use the input in another module. I'm having a hard time trying to do this because it's inside a function and I can't find any answers online.

I have two Python files:

gui.py

from tkinter import *

window = Tk()

entry = Entry(window)
entry.pack()

def get_input():
    user_input = entry.get()

btn = Button(window, text='Get Entry Input', command=get_input)
btn.pack()

window.mainloop()

Here's my second Python file where I want to use the user_input.

main.py

import gui

show_user_input = gui.user_input
print(show_user_input)

# Obviously this method wouldn't work but I don't know what to do.
# Please help

1 Answer 1

1

This will allow you to call a function from another module when the button is pressed and pass the value of the entry box.

Note, there is a small issue that we need to fix. The command argument requires a function that has no parameters. We can use a lambda function to fix this issue. A lambda function is an anonymous function that can have 0 to many parameters, but must consist of only one expression.

We use lambda: to indicate our function has no parameters. lambda x: would be a function that has one parameter, x. It's the same idea to add more parameters. The expression we need to execute when the button is pressed is just a call to main.show_input, which is what is done. I also added a no lambda version of gui.py. It might help understand what's happening.

main.py

def show_input(x):
    print(x)

gui.py

from tkinter import *
import main

window = Tk()

entry = Entry(window)
entry.pack()

btn = Button(window, text='Get Entry Input', command=lambda: main.show_input(entry.get()))
btn.pack()

window.mainloop()

gui.py no lambda

from tkinter import *
import main

def call_show_input():
    main.show_input(entry.get())

window = Tk()

entry = Entry(window)
entry.pack()

btn = Button(window, text='Get Entry Input', command=call_show_input)
btn.pack()

window.mainloop()
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Steve! It worked, but I don't quite get how lambda works. I'm fairly new to tkinter and Python and this is kind of making me dizzy. You say that lambda is used to take an argument and to call a function, so that means that the parameter x for the function show_input are just empty parameters? Or useless parameters?
@kroogs I added some more details about lambda functions and also added a gui.py version with no lambda to help understand what's happening.
Thanks again, Steve. I understand it better now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.