Python Forum
[Tkinter] Creation of Buttons with Shared Command Inside Class - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: GUI (https://python-forum.io/forum-10.html)
+--- Thread: [Tkinter] Creation of Buttons with Shared Command Inside Class (/thread-28179.html)



Creation of Buttons with Shared Command Inside Class - MulliganAgain - Jul-08-2020

I am trying to refactor some code into classes and methods that I have for a LED matrix GUI. When I create the matrix of buttons I created a lambda to recall the number of the button when it was created, but when I click a button it gives an error. This line of code worked when it was not inside a class but now that its transferring the variable "i" to a method within the class it just says the argument is missing when I click a button. please ignore errors within the click method. I cant really move on while this is not working so the click method is not finished being adjusted to the class.

Error:
File "C:\python_gui\LEDMATRIX.py", line 40, in <lambda> self.b = tk.Button(self.window, text="*", command=lambda i=self.but_num: ButtonMatrix.click(i)) TypeError: click() missing 1 required positional argument: 'i'


def makematrix(self):
        self.but_num=0
        #create matrix of buttons
        for row in range(1, self.num_leds[0]+1):
            for column in range(self.num_leds[1]):
                self.b = tk.Button(self.window, text="*", command=lambda i=self.but_num: ButtonMatrix.click(i))
                if (row % 2) == 0:
                    self.b.grid(row=row, column=33-column, padx=self.pad, pady=self.pad, columnspan=2)
                else:
                    if row == 1:
                        self.b.grid(row=row, column=column, padx=self.pad, pady=self.pad, columnspan=1)
                    else:
                        self.b.grid(row=row, column=column, padx=self.pad, pady=self.pad, columnspan=3)
                self.but_num+=1
                self.button.append(self.b)    
def click(self, i):
    if self.button[i].cget('bg') == self.values[LEDcolorslide.get()]:
        self.button[i].config(bg=self.values[bgLEDcolorslide.get()])
    else:
        self.button[i].config(bg=self.values[LEDcolorslide.get()])



RE: Creation of Buttons with Shared Command Inside Class - Yoriz - Jul-08-2020

Don't call the class click method ButtonMatrix.click(i) call self's click method self.click(i)