【问题标题】:class with Button as parent has no attribute "tk"以 Button 为父类的类没有属性“tk”
【发布时间】:2016-03-21 14:08:10
【问题描述】:

我最近正在编写一些代码,我想在其中创建另一个以按钮为父类的类(这是因为我想要一个按钮具有普通按钮所没有的各种方法),如下所示:

from tkinter import *
class some_class(Button):
    def __init__(self,parent):
        pass
    #i will put more here 
root = Tk()
button = some_class(root)
button.pack()
mainloop()

但这样做会产生错误:

AttributeError: 'some_class' object has no attribute 'tk'

然后,如果我添加像 text = "hello" 这样的关键字,我会收到错误:

TypeError: __init__() got an unexpected keyword argument 'text'

我对课程相对较新,所以任何关于为什么会发生这种情况的帮助将不胜感激。

【问题讨论】:

    标签: python class inheritance button tkinter


    【解决方案1】:

    您必须在课堂上使用Button.__init__ 来创建 tkinter 按钮。

    from tkinter import *
    
    
    class MyButton(Button): # CamelCase class name
    
        def __init__(self, parent):
            Button.__init__(self, parent)
            # or
            #Button.__init__(self, parent, text="hello")
    
    
    root = Tk()
    
    button = MyButton(root)
    button.pack()
    
    root.mainloop()
    

    如果您需要在课堂上使用text="hello" 或其他参数 然后使用*args, **kwargs

    from tkinter import *
    
    
    class MyButton(Button):
    
        def __init__(self, parent, *args, **kwargs):
            Button.__init__(self, parent, *args, **kwargs)
    
    
    root = Tk()
    
    button = MyButton(root, text='Hello World!')
    button.pack()
    
    root.mainloop()
    

    【讨论】:

    • 非常感谢!这真的很有帮助。
    猜你喜欢
    • 1970-01-01
    • 2021-11-22
    • 2021-11-03
    • 1970-01-01
    • 2019-10-31
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多