【问题标题】:Accessing inherited method from Toplevel从顶层访问继承的方法
【发布时间】:2013-08-08 14:14:22
【问题描述】:

Toplevel 有一个方法 distroy,我无法从类内部访问该方法。

此代码有效:

top = Toplevel()
Message(top, text="bla bla bla...").pack()
Button(top, text="Dismiss", command=top.distroy).pack()
top.mainloop() 

这不是:

from Tkinter import Toplevel,Message,Button,mainloop

class Demo(Toplevel):
    def __init__(self,title,message,master=None):
        Toplevel.__init__(self,master)
        self.title = title
        msg = Message(self,text=message)
        msg.pack()
        button = Button(self, text="Dismiss", command=self.distroy)
        button.pack()

if __name__ == '__main__':
    t1 = Demo("First Toplevel", "some random message text... goes on and on and on...")
    t2 = Demo("No, I don't know!", "I have no idea where the root window came from...")

    mainloop()

错误信息:

Traceback (most recent call last):
  File "C:\Users\tyler.weaver\Projects\python scripts\two_toplevel.pyw", line 16, in <module>
    t1 = Demo("First Toplevel", "some random message text... goes on and on and on...")
  File "C:\Users\tyler.weaver\Projects\python scripts\two_toplevel.pyw", line 12, in __init__
    button = Button(self, text="Dismiss", command=self.distroy)
AttributeError: Demo instance has no attribute 'distroy'

【问题讨论】:

  • 另外,你说的代码实际上并没有(我运行它),因为那里的“destroy”也拼错了。

标签: python python-2.7 tkinter


【解决方案1】:

那是因为你拼错了“destroy”:

from Tkinter import Toplevel,Message,Button,mainloop

class Demo(Toplevel):
    def __init__(self,title,message,master=None):
        Toplevel.__init__(self,master)
        self.title = title
        msg = Message(self,text=message)
        msg.pack()
        # Use "self.destroy", not "self.distroy"
        button = Button(self, text="Dismiss", command=self.destroy)
        button.pack()

if __name__ == '__main__':
    t1 = Demo("First Toplevel", "some random message text... goes on and on and on...")
    t2 = Demo("No, I don't know!", "I have no idea where the root window came from...")

    mainloop()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-18
    • 2021-05-07
    • 2010-10-01
    • 1970-01-01
    相关资源
    最近更新 更多