How to Add Label in Tkinter in Python: Simple Guide
To add a label in Tkinter in Python, create a
Label widget with the parent window and text, then use pack() or another geometry manager to display it. For example, label = tk.Label(root, text='Hello') creates the label, and label.pack() shows it on the window.Syntax
The basic syntax to add a label in Tkinter is:
Label(parent, text='Your text'): Creates a label widget inside theparentwindow or frame with the displayed text.label.pack(): Displays the label on the window using the pack geometry manager.
python
label = Label(parent, text='Your text')
label.pack()Example
This example creates a simple window with a label that says "Hello, Tkinter!". It shows how to import Tkinter, create the main window, add a label, and run the app.
python
import tkinter as tk root = tk.Tk() root.title('Label Example') label = tk.Label(root, text='Hello, Tkinter!') label.pack() root.mainloop()
Output
A small window titled 'Label Example' appears with the text 'Hello, Tkinter!' centered inside.
Common Pitfalls
Common mistakes when adding labels in Tkinter include:
- Forgetting to call
pack(),grid(), orplace()to display the label, so it won't appear. - Using
Labelwithout prefixing withtk.if you imported Tkinter asimport tkinter as tk. - Not creating a main window (
Tk()) before adding widgets.
python
import tkinter as tk root = tk.Tk() # Wrong: Label created but not displayed label = tk.Label(root, text='Missing pack()') # Right: Add pack() to show label label.pack() root.mainloop()
Output
A window appears with the label text 'Missing pack()' visible.
Quick Reference
| Method | Purpose |
|---|---|
| Label(parent, text='text') | Create a label widget with given text |
| label.pack() | Display the label using pack geometry manager |
| label.grid(row=0, column=0) | Display label using grid layout (alternative) |
| label.place(x=10, y=10) | Display label at specific position |
Key Takeaways
Create a label with Label(parent, text='your text') and display it with pack(), grid(), or place().
Always create a main window with Tk() before adding widgets.
Remember to call a geometry manager method like pack() to make the label visible.
Use the correct Tkinter import style and prefix widget names accordingly.
Labels are simple text displays useful for showing information in your GUI.