The LabelFrame widget

The LabelFrame widget is included with your normal tkinter import and also has a ttk version. Its purpose is to write a label and draw a border around a group of widgets. The label can be either some static text or a reference to a Label widget.

To demonstrate a possible use of this widget, let's make a small script:

import tkinter as tk
import tkinter.ttk as ttk

win = tk.Tk()
name_frame = ttk.Frame(win)
address_frame = ttk.Frame(win)

name_label_frame = ttk.LabelFrame(name_frame, text="Name")
address_label = ttk.Label(win, text="Address")
address_label_frame = ttk.LabelFrame(address_frame, labelwidget=address_label)

Our demonstration window will contain some information collection fields for the user's name and address. We will group these two pieces of information into their own LabelFrame widgets to give them a nice heading.

To define the text to show on the LabelFrame widget, we can either pass the text keyword argument, as we do with our name_label_frame, or we can pass a Label widget to the labelwidget argument (as seen for our address_label_frame):

first_name = ttk.Entry(name_label_frame)
last_name = ttk.Entry(name_label_frame)

first_name.pack(side=tk.TOP)
last_name.pack(side=tk.BOTTOM)

name_label_frame.pack(fill=tk.BOTH, expand=1)
name_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

We begin with the name collection, which we do using two Entry widgets. These widgets are packed into the LabelFrame widget in the same way as they would be added to a regular Frame widget:

address_1 = ttk.Entry(address_label_frame)
address_2 = ttk.Entry(address_label_frame)
address_3 = ttk.Entry(address_label_frame)

address_1.pack(side=tk.TOP)
address_2.pack(side=tk.TOP)
address_3.pack(side=tk.TOP)

address_label_frame.pack(fill=tk.BOTH, expand=1)
address_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=1)

win.mainloop()

We can then do the same thing with the Entry widget addresses, which are packed into our address_label_frame.

Give this file a run and you should see how LabelFrame looks:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset