g_odim_3
g_odim_3

Reputation: 117

How to get a button text in a function - tkinter?

How to get the specific button (that triggered the function) text in a function?

from tkinter import *
root = Tk()


def clicked():
    message = Label(root,text=f"You clicked {help?} button.")
    message.pack()

button0= Button(root,text="Nice day for coding ain't it?",state=ACTIVE,padx=200,pady=5,command=clicked)
button1= Button(root,text="What does evil Morty want?",state=ACTIVE,padx=200,pady=5,command=clicked)
button2= Button(root,text="Microsoft Edge==Chrome downloader",state=ACTIVE,padx=200,pady=5,command=clicked)
button3= Button(root,text="Only real programmers use Mac",state=ACTIVE,padx=200,pady=5,command=clicked)

EDIT: I think I have found an appropriate solution

from tkinter import *
root = Tk()


def clicked(text):
    print(text)
    

button0= Button(root,text="Suit up!",state=ACTIVE,padx=200,pady=5,command=lambda: clicked(button0.cget('text')))
button1= Button(root,text="Java should hide from kotlin",state=ACTIVE,padx=200,pady=5,command=lambda: clicked(button1.cget('text')))
button2= Button(root,text="Could it be more boring?",state=ACTIVE,padx=200,pady=5,command=lambda: clicked(button2.cget('text')))
button3= Button(root,text="Bazinga",state=ACTIVE,padx=200,pady=5,command=lambda: clicked(button3.cget('text')))

button0.pack()
button1.pack()
button2.pack()
button3.pack()

root.mainloop() 

Upvotes: 3

Views: 830

Answers (1)

martineau
martineau

Reputation: 123463

You can do it by making the command a lambda function with an argument that has a default value that's what you want passed to it. Below is an example of what I mean. The slightly tricky part is creating the lambda with an argument that is the widget it is with. In the code below, this is done by separating the Button creation from the configuring its command option, which is now done after they all exist.

from tkinter import *

root = Tk()

def clicked(btn):
    btn_text = btn.cget('text')
    message = Label(root, text=f'You clicked button "{btn_text}".')
    message.pack()

buttons = [
    Button(root, text="Nice day for coding ain't it?", state=ACTIVE, padx=200, pady=5),
    Button(root, text="What does evil Morty want?", state=ACTIVE, padx=200, pady=5),
    Button(root, text="Microsoft Edge==Chrome downloader", state=ACTIVE, padx=200, pady=5),
    Button(root, text="Only real programmers use Mac", state=ACTIVE, padx=200, pady=5),
]

for button in buttons:
    button.config(command=lambda btn=button: clicked(btn))
    button.pack(fill=X)

root.mainloop()

Upvotes: 1

Related Questions