tags:

views:

34

answers:

2

hi,

I'm new to TKinter and I was wondering if I can display a sequence of widgets on the same row instead of placing them one below the other one in a column.

I'm currently using frames to place my components, however if I have several widgets (buttons) in a frame, I would prefer to directly place the button as I want instead of creating additional subframes.

Thanks

+1  A: 

Use grid geometry manager manual

Andrey Gubarev
+3  A: 

You use geometry managers to lay out widgets within a container. Tkinter's geometry managers are grid, pack and place.

grid allows you to lay out your widgets in rows and columns. pack allows you to lay out your widgets along sides of a box (and great for making single horizontal or vertical columns). place lets you use absolute and relative positioning. In practice, place is used very infrequently.

In your case, you want to create a horizontal row of buttons which is typically done by creating a frame that represents the row, and then using pack to place the widgets side by side. Don't be afraid of using subframes for layout -- that is exactly what they are for.

For example:

import Tkinter as tk

class App:
    def __init__(self):
        self.root = tk.Tk()
        # this will be the container for a row of buttons
        # a background color has been added just to make
        # it stand out.
        container = tk.Frame(self.root, background="#ffd3d3")

        # these are the buttons. If you want, you can make these
        # children of the container and avoid the use of "in_" 
        # in the pack command, but I find it easier to maintain
        # code by keeping my widget hierarchy shallow.
        b1 = tk.Button(text="Button 1")
        b2 = tk.Button(text="Button 2")
        b3 = tk.Button(text="Button 3")

        # pack the buttons in the container. Since the buttons
        # are children of the root we need to use the in_ parameter.
        b1.pack(in_=container, side="left")
        b2.pack(in_=container, side="left")
        b3.pack(in_=container, side="left")

        # finally, pack the container in the root window
        container.pack(side="top", fill="x")

        self.root.mainloop()

if __name__ == "__main__":
    app=App()
Bryan Oakley
@Bryan Oakley Perfect thanks. One more thing, how can I specify the spacing between the components ? (For example, add some left marging before each button)
Patrick
@Patrick: use options like "padx" and "pady" in the pack command.
Bryan Oakley