Tkinter's Place Layout Manager (Python)

vegaseat 1 Tallied Votes 569 Views Share

There are times when you have to layout widgets on a window area fairly well spaced apart. To do this with pack() or grid() will be more than frustrating, for these occasions place() with its absolute coordinates comes to the rescue. Here is some Python/Tkinter GUI code showing you how place() is used. Also thrown in is code to generate random color hex strings acceptable by Tkinter.

# using geometry manager Tkinter.Place for layouts
# tested with Python24     vegaseat    28apr2007

import Tkinter as tk
import random as  rn


root = tk.Tk()

# window geometry is width x height + x_offset + y_offset (no spaces!)

# create 5 labels with a loop
texts = ['one', 'two', 'three', 'four', 'five']
labels = range(5)
for k in range(5):
    # create hex random color string acceptable to Tkinter eg. #ff0507
    rcolor = '#' + "".join(["%02x"%rn.randrange(256) for x in range(3)])
    # anchor='nw' is default, can set width and height in pixels
    labels[k] = tk.Label(root, text=texts[k], bg=rcolor)
    labels[k].place(x=0, y=(k)*25, width=100, height=20)

# more labels ...
label1 = tk.Label(root, text='label1', bg='yellow')
label2 = tk.Label(root, text='label2', bg='yellow')

# position these two lables at points x, y
# (x=0, y=0 is upper left corner of root area), y= 20, width=100, height=20), y= 200, width=100, height=20)