Search code examples
pythontkintersuperclasskeyword-argument

Problem adding a kwarg to tk.Button subclass


I would like to add a kwarg to a tk.Button subclass. The idea is that I would like to be able to add a number to each button of this subclass, and be able to call that number later on.

import tkinter as tk

class Test(tk.Tk):

    def __init__(self, tasks=None):
        super().__init__()


        self.title("Test")
        self.geometry("400x600")

        self.container = tk.Frame(self)
        self.container.pack()

        self.button1 = My_buttons(self.container, text="Button 1", number=1).grid(row=0, column=0)

        print(self.button1.index) #here is where I would like to be able to print 1

class My_buttons(tk.Button):

    def __init__(self, parent, *args, **kwargs):

        super(My_buttons, self).__init__(parent, *args, **kwargs)
        self.number = kwargs.pop("number")


if __name__ == "__main__":
    test = Test()
    test.mainloop()

The above just tells me that I have a "_tkinter.TclError: unknown option "-number"" error. Any help would be greatly appreciated! Thank you!


Solution

  • In My_buttons class, move self.number = kwargs.pop("number") to be before the call to super(). this way you will not pass the number keyword argument to Button constructor.

    also, you should split:

    self.button1 = My_buttons(self.container, text="Button 1", number=1).grid(row=0, column=0)
    

    into:

    self.button1 = My_buttons(self.container, text="Button 1", number=1)
    self.button1.grid(row=0, column=0)
    

    And I guess, replace print(self.button1.index) with print(self.button1.number).