开发者

Understanding Python Classes, In an attempt to make Custom widgets

I'm trying to create a class called Menu, which would create a right-click menu for whichever widget is given to it. In this case self.Label.

However, when I run my program I get the following error:

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开发者_StackOverflow "C:\Python26\Lib\Tkinter.py", line 1901, in _setup
    self.tk = master.tk
AttributeError: B3Menu instance has no attribute 'tk'

My Program:

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()

This is my first attempt at creating a widget using Pythons class system. So I'm sure I'm doing many things wrong. Any help would be much appreciated.


Maybe you should try inheriting from some base widget class?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜