Building Custom Labels with Tkinter and ttkbootstrap in Python Tutorial
In this tutorial, we’ll walk through the process of creating a label using the Tkinter (ttkbootstrap) library in Python. Tkinter is the standard GUI toolkit for Python, and when combined with ttkbootstrap, it enhances the look and feel of your applications with modern, attractive themes.
Full tutorial + Source Code
Installing ttkbootstrap
Before we dive into creating labels, ensure that you have Tkinter and ttkbootstrap installed. You can install ttkbootstrap via pip if it’s not already installed
pip install ttkbootstrap
Creating a Label Using ttkbootstrap
Now, let’s create the label. We will use the ttk.Label()
widget, which allows for advanced styling with ttkbootstrap themes.
Here is the full code to create the Label.
# Import the ttkbootstrap library
import ttkbootstrap
# Create the main window of the application
root = ttkbootstrap.Window()
# Set the title of the window that will appear on the title bar
root.title('Labels in Tkinter (ttkbootstrap) ')
# Define the size of the window (600 pixels wide and 200 pixels high)
root.geometry('600x200') # width x height
# Create a label widget with the text 'My Label'
MyLabel = ttkbootstrap.Label(text = 'My Label')
# Place the label inside the window using .pack() method with 30 pixels of vertical padding
MyLabel.pack(pady = 30)
# Start the Tkinter event loop to display the window and keep it open
root.mainloop()
The .pack()
method is one of the most commonly used geometry managers in Tkinter. It automatically places the widget in the available space
Selecting a Font and Changing Font size in Tkinter
In Tkinter (ttkbootstrap), you can select a font and change the font size of widgets, including labels, buttons, and other text-based widgets.
To change the font in Tkinter (ttkbootstrap), you need to specify the font as a tuple. The tuple should contain:
- The font family (e.g.,
"Arial"
,"Helvetica"
,"Courier"
) - The font size (e.g.,
12
,16
,20
) - The font style (optional) like
"bold"
,"italic"
, or"underline"
Here is the code to illustrate the Font.
import ttkbootstrap
root = ttkbootstrap.Window()
root.title('Labels in Tkinter (ttkbootstrap) ')
root.geometry('600x400') # width x height
MyLabel1 = ttkbootstrap.Label(text = 'Times New Roman Font',font=('Times New Roman',18,'bold'))
MyLabel2 = ttkbootstrap.Label(text = 'Times New Roman Font',font=('Times New Roman',18,'italic'))
MyLabel3 = ttkbootstrap.Label(text = 'Comic Sans MS Font' ,font=('Comic Sans MS' ,18,))
MyLabel4 = ttkbootstrap.Label(text = 'Comic Sans MS Font' ,font=('Comic Sans MS' ,18,'bold'))
MyLabel1.pack(pady = 30)
MyLabel2.pack(pady = 30)
MyLabel3.pack(pady = 30)
MyLabel4.pack(pady = 30)
root.mainloop()
Here is the output of the code.