2

I'm trying to start a Tkinter application that follows Class menu in Tkinter Gui for neatness but also add this functionality for e.g. Button bars, RadioButton bars, etc. Something like:

from Tkinter import *

def clickTest():
    print "Click!"

class App(Tk):
    def __init__(self):
        Tk.__init__(self)
        menuBar = MenuBar(self)
        buttonBar = ButtonBar(self)

        self.config(menu=menuBar)
        buttonBar.grid(row=0, column=0) ???

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

        fileMenu = Menu(self, tearoff=False)
        self.add_cascade(label="File", menu=fileMenu)
        fileMenu.add_command(label="Exit", command=clickTest)

class ButtonBar(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        firstButton = Button(parent, text="1st Button", command=clickTest)
        secondButton = Button(parent, text="2nd Button", command=clickTest)

if __name__ == "__main__":

    app = App()
    app.mainloop()

But I'm not sure how to get all of this to show up in the same window. Of course, the code as-is doesn't work. Any suggestions are appreciated. Thanks!

Community
  • 1
  • 1
Ryan
  • 129
  • 2
  • 8

1 Answers1

1

Did it with pack(). I am sure it can also be done with grid() but i am not much familiar with it.

from Tkinter import *

def clickTest():
    print "Click!"

class App(Tk):
    def __init__(self):
        Tk.__init__(self)
        menuBar = MenuBar(self)
        buttonBar = ButtonBar(self)

        self.config(menu=menuBar)
        buttonBar.pack()

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

        fileMenu = Menu(self, tearoff=False)
        self.add_cascade(label="File", menu=fileMenu)
        fileMenu.add_command(label="Exit", command=clickTest)

class ButtonBar(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        firstButton = Button(self, text="1st Button", command=clickTest).pack()
        secondButton = Button(self, text="2nd Button", command=clickTest).pack()

if __name__ == "__main__":

    app = App()
    app.mainloop()

Another thing is, you should set buttons parent as Frame like in this line:

firstButton = Button(self, text="1st Button", command=clickTest).pack()

Here i changed parent with self. self is the Frame itself, not the whole toplevel window. And with pack() function i packed the button in its parent which in this case the Frame.

Then with buttonBar.pack() i packed the buttonBar in toplevel window. You can also use grid here and in Frame.

username
  • 4,258
  • 1
  • 16
  • 26
  • Cool. Thanks. Yeah, I just figured it out, too, with grid(). Thanks for the last suggestion for button's parent -- that fixed it for me. – Ryan Apr 18 '12 at 01:47