tomek pro
tomek pro

Reputation: 3

tkinter - LabelFrame not displaying label

I am trying to create a LabelFrame in tkinter, however the "title" of the frame is not displayed, neither is the border around the LabelFrame.

Minimal example:

import tkinter as tk

root = tk.Tk()
root.title("Test")
root.geometry("400x400")

instance = tk.Label(root, text="SCTL:").pack()

labelframe = tk.LabelFrame(root, text="Title of Frame").pack()
instance2 = tk.Label(labelframe, text="some text").pack(padx=10, pady=10)

root.mainloop()

This example will get "some text" displayed, however "Title of Frame" will not. I am using Python 3.8.8 and tkinter 8.6.10. Does anybody have an idea how I can get the title of the frame and its border to be displayed?

Thank you in advance!

Upvotes: 0

Views: 918

Answers (1)

typedecker
typedecker

Reputation: 1370

So the problem here is that you are initializing and packing the labelframe in the same line as @jasonharper pointed out -: labelframe = tk.LabelFrame(root, text="Title of Frame").pack().

Note that this does not work, since the variable labelframe does not get assigned the newly initialized labelframe object but rather the return value of the called function pack.

This means that if we write the same in two different lines, one for object initialization and the other for packing, the problem disappears. Like so -:

labelframe = tk.LabelFrame(root, text="Title of Frame") # First initialize the object and store it in the variable.
labelframe.pack() # Then use the variable to pack it.

In general also if a tkinter widget is to be used for long term in a program I suggest not packing it in the same line as it's initialization, this not only looses the newly initialized object's reference but also can cause such problems.

But the same if is temporary then can be done in one line. Here you were using the LabelFrame in the next line and thus should have separately done the packing and the initialization.

Upvotes: 1

Related Questions