Skip to content Skip to sidebar Skip to footer

Working On A Way To Return The Text Of A Button After The Button Is Clicked In Tkinter

I'm trying to create a list of buttons that are clicked with this lambda function: button1.config(command=(lambda x: (clicked.append(x)))(button1.cget('text'))) It seems to sort o

Solution 1:

Trying to do all this in a lambda is the wrong approach. It's simply too confusing, if not impossible to do what you want. Instead, create a method that does the work, and use lambda only as a way to call that function:

from Tkinter import *
classGraphicsInterface:

    def__init__(self):
        self.window = Tk()
        self.window.geometry("720x500")

        self.clicked=[]
        button1 = Button(self.window, text="Dice 1", width=13)
        button2 = Button(self.window, text="Dice 2", width=13)
        button1.pack()
        button2.pack()

        button1.configure(command=lambda btn=button1: self.OnClick(btn))
        button2.configure(command=lambda btn=button2: self.OnClick(btn))

        self.window.mainloop()

    defOnClick(self, btn):
        text = btn.cget("text")
        self.clicked.append(text)
        print"clicked:", self.clicked

app = GraphicsInterface()

Solution 2:

One way would be to bind the button click event to a function which appends the text to your clicked list. For example,

    self.clicked=[]

    self.button1 = Button(self.window, text="Dice 1", width=13)
    self.button1.place(x=60, y=160)
    self.button1.bind("<Button-1>",self.callback)


defcallback(self,event):
    self.clicked.append(event.widget.cget("text"))

You could then add other buttons that also call callback, and get their text through the event parameter.

Post a Comment for "Working On A Way To Return The Text Of A Button After The Button Is Clicked In Tkinter"