Python Tkinter Basics: An Introduction to Tkinter UI with the Place Layout
Tkinter is a popular library for creating user interfaces with Python. In this tutorial you will learn the usage of the Place-Layout
The Place layout allows you to specify the exact position and size of each widget using absolute coordinates. It's useful for creating complex layouts, but it requires a lot of manual positioning.
To use the place layout we have to call the place method. This method accepts following parameters:
- x: The X coordinate of the upper-left corner of the widget, relative to the parent widget's upper-left corner.
- y: The Y coordinate of the upper-left corner of the widget, relative to the parent widget's upper-left corner.
- width: The width of the widget.
- height: The height of the widget.
- relx: The relative X coordinate of the upper-left corner of the widget, as a percentage of the parent widget's width.
- rely: The relative Y coordinate of the upper-left corner of the widget, as a percentage of the parent widget's height.
- relwidth: The relative width of the widget, as a percentage of the parent widget's width.
- relheight: The relative height of the widget, as a percentage of the parent widget's height.
- anchor: Specifies where the widget should be anchored within its parent widget. This can be a combination of the following values: 'n', 's', 'e', 'w': The widget should be anchored to the top, bottom, right, or left side of its parent, respectively. 'nw', 'ne', 'sw', 'se': The widget should be anchored to the top-left, top-right, bottom-left, or bottom-right corner of its parent, respectively.
- bordermode: Specifies how the widget's size should be calculated. This can be one of the following values: 'inside': The widget's size is calculated based on its internal dimensions, without including any border or padding. 'outside': The widget's size is calculated based on its external dimensions, including any border or padding.
The example below shows the usage of the place-layout with the same layout which we already implemented in the previous tutorial for the grid-layout:
import tkinter as tk
root = tk.Tk()
# Create the text input and submit button using the Place layout
text_input = tk.Entry(root)
submit_button = tk.Button(root, text="Submit")
text_input.place(x=10, y=10, width=200, height=25)
submit_button.place(x=220, y=10, width=75, height=25)
# Create the multiline label using the Place layout
label_text = tk.StringVar()
label_text.set("This is a multiline label.\nIt takes up all available width.\nDemo for place layout with Tk in Python\n(c) DEVLABS.ninja")
multiline_label = tk.Label(root, textvariable=label_text, justify="left", anchor="w", wraplength=root.winfo_screenwidth())
multiline_label.place(x=10, y=50, relwidth=1.0, relheight=1.0, width=-20, height=-60)
root.mainloop()