Skip to content
Advertisement

Tkinter passing parameters

I have 2 .py files in the same project, one called namer and the other called GuiApp

In namer is

def nameit(name):
    greetings = f'Hello {name}'
    print(greetings)

GuiApp holds:

from tkinter import *
from namer import nameit
from functools import partial

window = Tk()
window.geometry("300x300")
txt = Entry(window, width=20)
txt.grid(row=4, column=3)
l1 = Label(window, text="Output", font=15)
l1.grid(row=6, column=0)
Btn = Button(window, text="Run X", fg="black", bg="gray", command=(nameit(txt.get())))
Btn.grid(row=4, column=2)

window.mainloop()

I don’t understand why when i type something into txt, it is not returned as part of the nameit function. Any ideas please as im new to Tkinter?

Advertisement

Answer

When the command of a button has parenthesis, it makes it call the function. So, create an anonymous function like: lambda: nameit(txt.get())

Solution:

from tkinter import *
from namer import nameit
from functools import partial

window = Tk()
window.geometry("300x300")
txt = Entry(window, width=20)
txt.grid(row=4, column=3)
l1 = Label(window, text="Output", font=15)
l1.grid(row=6, column=0)
Btn = Button(window, text="Run X", fg="black", bg="gray", command=lambda: nameit(txt.get()))
Btn.grid(row=4, column=2)

window.mainloop()
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement