0

I'm a beginner in Python and I'm trying to build some GUI to understand. I want to pass to a button a function that requies a parameter, but when I launch the script, it does not work. I'm attaching a python file.

from tkinter import *
from tkinter import messagebox



window = Tk()
window.title("Hello World")
window.geometry('350x200')


def clicked(msg):
    messagebox.showinfo("Message",msg)



text = Entry(window,width=100)
text.grid(column = 1, row = 0)

btn = Button(window,text = "Click me",command = clicked(text.get()))
btn.grid(column=5, row=1)
window.mainloop()

2 Answers2

0

The following fix is required for your file:

When you assign the command parameter, it wont wait till your click on button, it will pop out the message box right after your tkinter application execution. (Thats what i experienced when i executed your code)

You have to use lambda here

So you can fix this by:

btn.bind('<Button-1>',lambda event: clicked('Your Text')) # Button-1 stands for left mouse click

More on bind() method: https://effbot.org/tkinterbook/tkinter-events-and-bindings.htm


This is the final code:

from tkinter import *
from tkinter import messagebox



window = Tk()
window.title("Hello World")
window.geometry('350x200')


def clicked(msg):
    messagebox.showinfo("Message",msg)


text = Entry(window,width=100)
text.grid(column = 1, row = 0)

btn = Button(window,text = "Click me")
btn.bind('<Button-1>',lambda event: clicked(text.get()))
btn.grid(column=5, row=1)
window.mainloop()
JimShapedCoding
  • 849
  • 1
  • 6
  • 17
0

The command will be executed when the code is interpreted, to avoid that you can use lambda to pass an argument to the function

command = lambda : clicked(text.get()))

Or you can use partial which will return a callable object that behaves like a function when it is called.

from functools import partial
...
command = partial(clicked, text.get()))
Kenly
  • 24,317
  • 7
  • 44
  • 60