0
我試圖創建一個名爲Menu的類,它將創建一個右鍵單擊菜單,無論哪個窗口小部件給它。在這種情況下,self.Label。瞭解Python類,試圖使自定義窗口小部件
然而,當我運行我的程序,我得到以下錯誤:
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()
這是我在創建使用蟒蛇類系統部件的第一次嘗試。所以我確定我做了很多錯誤的事情。任何幫助將非常感激。