Oct-18-2020, 07:41 PM
Can anyone help me with a problem illustrated in the code below. I am instantiating three tkinter buttons and saving the objects in a list which is I think a fairly standard way of doing things. The buttons can then be managed, colour change, text etc by referencing them via their index in the list. But if a button is clicked it seems impossible to detect which button it was. The only button object that is "active", if you want to call it that, is the last one that was instantiated in the For loop. Which ever button is clicked, it is that object that handles the click event. Is there a way of detecting which button is clicked when they have been instantiated this way. Thank you for sharing your expertise.
JohnB
JohnB
import tkinter as tk root=tk.Tk() class Butman(tk.Frame): def __init__(self,MyNumber): self.MyNumber = MyNumber tk.Frame.__init__(self) def SetCol(self,col): self.but.config(bg = col) def SetText(self,Text): self.but.config(text = Text) def DoSomething(): print ("something done") frame2 = tk.Frame(bg="grey", height = 720 ,width = 1280) frame2.pack() ButObj = [] for x in range(0,3): B = Butman(x) B.but=tk.Button(frame2, state="normal", text="sometext",compound= tk.CENTER,font=('comicsans', 16),relief=tk.FLAT,command = lambda: DoSomething()) B.but.place(relx=x/4, rely=x/4, relwidth=0.18, relheight=0.18) ButObj.append(B) ButObj[1].SetCol("green") B.SetCol("red")