向 tk.Button 子类添加 kwarg 时出现问题

Problem adding a kwarg to tk.Button subclass

我想向 tk.Button 子类添加一个 kwarg。我的想法是,我希望能够为这个子类的每个按钮添加一个数字,并且稍后能够调用该数字。

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()

上面只是告诉我,我有一个“_tkinter.TclError:未知选项“-number””错误。任何帮助将不胜感激!谢谢!

My_buttons class 中,将 self.number = kwargs.pop("number") 移动到调用 super() 之前。这样你就不会将 number 关键字参数传递给 Button 构造函数。

另外,你应该分裂:

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

进入:

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

我想,用 print(self.button1.number) 替换 print(self.button1.index)