0

I know how to get the text from a single button by hardcoding the name of the button to the cget("text") command but, is there a way to make this function dynamic so that any button assigned to the command outputs it's text attribute?

So lets say I have this

`button1 = customtkinter.CTKButton(ButtonFrame, text="Button 1", font=('Arial', 14), command=output_text1)
button2 = customtkinter.CTKButton(ButtonFrame, text="Button 2", font=('Arial', 14), command=output_text2)

Instead of doing 

def output_text1():
    button_text = button1.cget("text")
    output = customtkinter.CTKLabel(Orderlist, text=button_text).pack 
    
def output_text 2():
    button_text = button1.cget("text")
    output = customtkinter.CTKLabel(Orderlist, text=button_text).pack()`

Is there any way to make one function to apply to all buttons so that the I don't have to make a function for each of the buttons I will create?

I am fairly new to tkinter and customtkinter so any help would be greatly appreciated. I looked through similar questions but I couldn't find a question where they dynamically get text based on button.

onexcent
  • 13
  • 2
  • You may find answer [here](https://stackoverflow.com/questions/35470943/tkinter-same-event-for-multiple-buttons). Basically you will need to use lambda function – Danya K Aug 06 '23 at 22:10

1 Answers1

0

Try with lambda function.

def output_text(button):
    button_text = button.cget("text")
    customtkinter.CTKLabel(Orderlist, text=button_text).pack()

button1 = customtkinter.CTKButton(ButtonFrame, text="Button 1", font=('Arial', 14), command=lambda: output_text(button1))
button2 = customtkinter.CTKButton(ButtonFrame, text="Button 2", font=('Arial', 14), command=lambda: output_text(button2))
Mayur Buragohain
  • 1,566
  • 1
  • 22
  • 42