我正在编写Python应用程序。
我使用Tkinter+PythonMegaWidgets是为了semplicity的原因。在
直奔主题,我需要扩展Tkinter.框架基类,通过添加一些提供额外功能的自定义成员函数。在
这些“自定义框架”将添加到Pmw笔记本对象。在
稍后,我需要从NoteBook中检索“自定义框架”实例,调用我添加的自定义成员函数;问题从这里开始。。。在
尽管有Duck类型的原则,但我无法访问这些“额外方法”中的任何一个,因为Pmw笔记本类只能返回框架对象!。在
我找不到任何解决办法。在
下面是一段详细描述我的问题的代码示例(更简单)。在from Tkinter import *
from Pmw import NoteBook
# I define a custom frame, by extending Tkinter.Frame baseclass
class CustomPanel(Frame):
def __init__(self, master, _text):
Frame.__init__(self, master)
self.label = Label(self, text=_text)
self.localVariable = "Hello, world!" # I define a new local variable
self.label.pack()
self.pack()
# I define a custom member function, which I _ABSOLUTELY_ want to be accessible.
def customMethod(self):
print self.localVariable
# main frame of application
class MyFrame(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.noteBook = NoteBook(self) # I create a NoteBook object...
tab1 = self.noteBook.add("tab 1") # then, I add one (empty) tabs to it
panel1 = CustomPanel(tab1, "hello")
self.button = Button(self, text="Call CustomMethod()!", command=self.callCustomMethod) # I add a button test
self.noteBook.grid()
self.button.grid(row=1)
self.pack()
self.mainloop()
# I define click handler for button,
def callCustomMethod(self):
panel1 = self.noteBook.page(0) # I try to get frame contained in current tab
# pane11 is supposed to be a 'CustomPanel' object;
try:
panel1.customMethod() # ...then, custom method should be accessible
except AttributeError:
print 'AttributeError!'
# for illustration purpose only, I show that Panel1 is a 'Frame'(superclass) object only!
print panel1.__class__
frame = MyFrame() # create a MyFrame instance
按下按钮,控制台输出为:
^{pr2}$
要预测反对意见:
1-设置panel1.class属性,如下所示try:
panel1.__class__ = CustomPanel
panel1.customMethod() # ...then, custom method should be accessible
except AttributeError:
print 'AttributeError!'
不起作用,因为customMethod()在任何情况下都不能访问localVariable,后者只在CustomPanel子类中声明
2-我甚至不能回忆CustomPanel构造函数,因为这将重置原始成员变量,我想用它们的原始值检索这些变量。在
感谢任何帮助。在
它