-1

I am trying to create binding in a loop using tkinter module.

from tkinter import *
class Gui(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)  
        self.parent = parent
        self.initUI()
    def Arrays(self,rankings):
        self.panels = {}
        self.helpLf = LabelFrame(self, text="Array Layout:")
        self.helpLf.grid(row=10, column=9, columnspan=5, rowspan=8)
        for rows in range(10):
            for cols in range(10):
                x  = str(rows)+"_"+str(cols)
                self.row = Frame(self.helpLf)
                self.bat = Button(self.helpLf,text=" ", bg = "white")
                self.bat.grid(row=10+rows, column=cols)
                self.panels[x] = self.bat
                self.panels[x].bind('<Button-1>', self.make_lambda())
                self.panels[x].bind('<Double-1>', self.color_change1)

    def color_change(self, event):
        """Changes the button's color"""
        self.bat.configure(bg = "green")
    def color_change1(self, event):
        self.bat.configure(bg = "red")

There are 10X10= 100 buttons here. the binder works only for the last button. Does anyone know how can I apply the binder for all the buttons?

Dubar Alam
  • 79
  • 1
  • 10

1 Answers1

3

You use self.bat in color_change1 but self.bat keeps last button because you ovewrite it in loop. But you keep all buttons in self.panels[x] to have access to any button. So you could use it.

But there is simpler solution - binding use variable event to send some information about event to executed function. For example event.widget give you access to widget which execute function color_change1 so you can use it:

def color_change1(self, event):
    event.widget.configure(bg = "red")

See "Event Attributes" on page Events and Bindings

furas
  • 134,197
  • 12
  • 106
  • 148