Home > OS >  How to access a variable containing input from entry box in tkinter and use it in another module?
How to access a variable containing input from entry box in tkinter and use it in another module?

Time:05-09

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

CodePudding user response:

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()
  • Related