我正在尝试创建一个名为Menu的类,它会为给定的小部件创建一个右键单击菜单。在这种情况下 self.Label 。
但是,当我运行程序时,我收到以下错误:
Traceback (most recent call last):
File "<string>", line 245, in run_nodebug
File "<module1>", line 57, in <module>
File "<module1>", line 55, in run
File "<module1>", line 52, in __init__
File "<module1>", line 12, in __init__
File "C:\Python26\Lib\Tkinter.py", line 2595, in __init__
Widget.__init__(self, master, 'menu', cnf, kw)
File "C:\Python26\Lib\Tkinter.py", line 1923, in __init__
BaseWidget._setup(self, master, cnf)
File "C:\Python26\Lib\Tkinter.py", line 1901, in _setup
self.tk = master.tk
AttributeError: B3Menu instance has no attribute 'tk'
我的计划:
import Tkinter
class B3Menu:
def __init__ (self, wid):
self.wid = wid
self.MeVar = Tkinter.StringVar()
self.Me = Tkinter.Menu(self, tearoff=0,
activebackground='grey15',
activeforeground='grey95')
self.Me.add_radiobutton(label='Cut', variable=self.MeVar,
command=self.menu_beh,
accelerator='Ctrl-x')
self.Me.add_radiobutton(label='Copy', variable=self.MeVar,
command=self.menu_beh,
accelerator='Ctrl-c')
self.Me.add_separator()
self.Me.add_radiobutton(label='Paste', variable=self.MeVar,
command=self.menu_beh,
accelerator='Ctrl-v')
self.wid.bind( "<ButtonRelease-3>", self.menu_pos )
def menu_pos (self, event=None):
self.Me.post( event.x_root, event.y_root )
def menu_beh (self):
''' Handles the behavior of right click menu '''
if self.MeVar.get() =='Cut':
self.wid.event_generate("<<Cut>>")
if self.MeVar.get() =='Copy':
self.wid.event_generate("<<Copy>>")
if self.MeVar.get() =='Paste':
self.wid.event_generate("<<Paste>>")
class Suite(Tkinter.Tk):
def __init__(self):
Tkinter.Tk.__init__(self)
self.Label = Tkinter.Label(self, text='hello')
self.Label.pack()
B3Menu(self.Label)
def run():
Suite().mainloop()
if __name__ == '__main__':
run()
这是我第一次尝试使用Pythons类系统创建一个小部件。所以我确定我做错了很多事。任何帮助将非常感激。
答案 0 :(得分:2)
也许你应该尝试继承一些基类小部件类?