views:

55

answers:

1

Hello,

I'm working on a Gui and I'd like to know if it is possible to make the menu property of a window a separate class on my script for a clearer and more enhancement prone code.

my code currently is :

class Application(Frame):
   """ main window application """
   def __init__(self, boss = None):
   (...)
   self.menu = Menu(self)
   self.master.config(menu = self.menu)

   self.select = Menu(self.menu)
   self.menu.add_cascade(label = 'Select', menu = self.select)
   self.select.add_command(label = 'Select all', command = self.select_all)
   ...

And I would prefer something like :

class MenuBar:

    # all the content of the menu here

class Application(Frame):
   (...)
   self.menu = MenuBar(self) ?

rgds,

A: 

Yes, it's possible:

import Tkinter
import sys

class MenuBar(Tkinter.Menu):
    def __init__(self, parent):
        Tkinter.Menu.__init__(self, parent)

        fileMenu = Tkinter.Menu(self, tearoff=False)
        self.add_cascade(label="File",underline=0, menu=fileMenu)
        fileMenu.add_command(label="Exit", underline=1, command=self.quit)

    def quit(self):
        sys.exit(0)

class App(Tkinter.Tk):
    def __init__(self):
        Tkinter.Tk.__init__(self)
        menubar = MenuBar(self)
        self.config(menu=menubar)

if __name__ == "__main__":
    app=App()
    app.mainloop()
Bryan Oakley
Hello , no it doesn't work : I get the error message "AttributeError: MenuBar instance has no attribute 'master'" .
Bruno
@Bruno: I edited my answer to give you a working example.
Bryan Oakley
@Bryan : Thanks for your answer, I've tried it and it works great but for a mysterious reason my script doesn't work. As soon as I find the answer I'll tell you !
Bruno
@Bryan : Everyting works great, thanks a lot !
Bruno