As an embedded designer, your task often involves crafting nimble programs to facilitate seamless communication with an array of devices, including data loggers ,data acquisition modules, Serial port monitors etc. Python emerges as the go-to language for engineers operating within the embedded domain, enabling the creation of such programs with ease.
While Python's native toolkit, tkinter, serves as a fundamental choice for creating graphical user interfaces (GUIs), its appearance may seem outdated to some. To address this, many opt for ttkbootstrap, a sleek and modern alternative. Not only does ttkbootstrap enhance the visual appeal of GUIs, but it also simplifies the development process compared to other GUI frameworks.
This tutorial is designed to get a Python novice started quickly on using ttkbootstrap to create beautiful Python interfaces. Tutorial assumes that the reader has some experience with Python language
The tutorial teaches the following
- Source Codes
- What is ttkbootstrap framework
- How to install ttkbootstrap using PIP
- How to create a Basic Window in tkinter/ttkbootstrap
- How to create a label in tkinter/ttkbootstrap
- change font type/font size of label text
- change label theme
- Creating and Using Entry Box widget in tkinter/ttkbootstrap
- Creating and Using Buttons in tkinter/ttkbootstrap
- Creating and Using Drop Down Combo boxes in tkinter/ttkbootstrap
- Creating and Using Scrollable TextBox (ScrolledText) in tkinter/ttkbootstrap
- Change Font Type/Font Size
- Read the input Text from ScrollableTextBox (ScrolledText)
- Running Periodic Background tasks in ttkbootstrap
- Convert tkinter (ttkbootstrap) Python script to a Windows executable using Pyinstaller
What is ttkbootstrap framework
Tkinter serves as Python's primary binding to the Tk GUI toolkit, offering a standardized interface for graphical user interfaces (GUIs) across Linux, Microsoft Windows, and macOS platforms. While Tkinter remains versatile and widely adopted, one notable drawback is its GUI elements' outdated appearance compared to other frameworks.
Enter ttkbootstrap – a theme extension designed specifically for Tkinter. By integrating ttkbootstrap, developers can imbue their Tkinter applications with sleek, modern flat-style themes inspired by Bootstrap.
ttkbootstrap comes packaged with a collection of beautifully styled light and dark themes, predefined styles for widgets, new gui widgets like Meter, DateEntry, and Floodgauge.You can see the widgets below.
Source Codes
Install ttkbootstrap on Windows
Make sure that python interpreter is installed on your system (Here our System is Windows ).
You can use any Python interpreter, here we are using CPython that is available with Standard Python Distribution.
Make sure that you add Python interpretor (python.exe) to the path variable on Windows system during install.
You can see the available modules by using the pip command.PIP comes preinstalled with Python interpreter.
On command line type
pip list
if ttkbootstrap not installed ,use PIP to install it using the below command.
pip install ttkbootstrap
You can check ttkbooststrap installed or not by using pip list command
Create a basic Window using ttkbooststrap
Here we will create a very basic window using ttkbooststrap (tkinter) and Python. Put the below code into your text editor,save it and run it.
import ttkbootstrap
root = ttkbootstrap.Window()
root.mainloop()
This will create a very basic window like the one below.
- You can control the size of the window using the root.geometry('widthxheight') method.
- You can add a title to the Window using root.title('your title for the Window') method.
root.mainloop() is simply a method in the main window that executes what we wish to execute in an application . This will loop forever until the user exits the window or waits for any events from the user. The mainloop automatically receives events from the window system and deliver them to the application widgets. This gets quit when we click on the close button of the title bar
You can set the theme of the Window using keyword themename
root = ttkbootstrap.Window(themename = 'superhero') # theme = superhero
or
#root = ttkbootstrap.Window(themename = 'cosmo')
Names of various pre-installed themes can be found in the ttkbootstrap website.
Now the full code is below
import ttkbootstrap
root = ttkbootstrap.Window(themename = 'litera') # select theme
root.geometry('400x900') # widthxheight
root.title('My ttkbootstrap Window') # name of window
root.mainloop()
You can use alias to shorten the ttkbootstrap
import ttkbootstrap as ttkb
then program becomes
import ttkbootstrap as ttkb #alias to shorten ttkbootstrap to ttkb
root = ttkb.Window(themename = 'litera') # ttkbootstrap.Window() to ttkb.Window()
root.geometry('400x900') # widthxheight
root.title('My ttkbootstrap Window')
root.mainloop()
Disable/Enable the Maximize Button on tkinter window
Here we will learn how to control the resize property of the tkinter/ttkbootstrap window.
In some cases we don't want the user of our application maximizing the application window.We can disable the maximize button on the window by calling the .resizable(x_axis,y_axis) method. It takes two arguments to disable or enable resize function in x or y axis.
root.resizable(0,0) #Disable resizing in all directions,Maximize button disabled
#root.resizable(x,y)
root.resizable(1,0) #Enable Resize in X direction only
#Disable resizing y direction only
root.resizable(0,1) #Disable Resize in X direction only
#Enable resizing y direction only
Detect and Handle Window Close Button Event in tkinter
- Occasionally, it becomes necessary to notify the user when they attempt to close a tkinter/ttkbootstrap window by pressing the close button, allowing them to reconsider their action.
- Sometimes we may need to close connection to file objects or database connections when the user presses the close button on the window.
So to do these things we may need to intercept and capture the Window Close Button Event in tkinter/ttkbootstrap framework and handle it our self.
When you press the close button on a tkinter window. the destroy() method of that window is called.
Tkinter supports a mechanism called protocol handlers. Here, the term protocol refers to the interaction between the application and the window manager.
The most commonly used protocol is called WM_DELETE_WINDOW, and is used to define what happens when the user explicitly closes a window using the window manager.
You can use the protocol method to install a handler for this protocol. The code below shows how to do it
#Python code for Detect and Handle Window Close Button Event in tkinter/ttkbootstrap
import ttkbootstrap as ttkb
def custom_exit_handler():
print ('You Clicked Exit Button')
#add custom code here
root.destroy()
root = ttkb.Window(themename = 'litera')
root.geometry('400x900') # widthxheight
root.title('My ttkbootstrap Window')
root.protocol("WM_DELETE_WINDOW", custom_exit_handler)
root.mainloop()
Here when you press the Close Button,
custom_exit_handler() function is called,a message is printed to terminal and the window is destroyed. You can add your custom code in that function before the window is destroyed.
Creating and Using Labels in tkinter/ttkbootstrap
import ttkbootstrap as ttkb
root = ttkb.Window(themename = 'litera')
root.geometry('400x400') # widthxheight
My_Label = ttkb.Label(text = "Hello World")
My_Label.pack()
root.mainloop()
Here, a label widget is created using the Label class provided by ttkbootstrap. The text displayed on the label is set to "Hello World".
My_Label.pack()
This line packs the label into the window. Packing is a way to organize widgets within a container in tkinter.
Here the Label is placed at the center ,since we are using .pack() method.
If you need precise and absolute placement you can use the .place() method as shown below.
My_Label = ttkb.Label(text = "Hello World")
My_Label.place(x=10,y=300)
You can also change the size and type of font on the Labels using
import ttkbootstrap as ttkb
root = ttkb.Window(themename = 'litera')
root.geometry('400x200') # widthxheight
My_Label_1 = ttkb.Label(text = "Helvetica 15",font = ('Helvetica',15) ).place(x=10,y=10)
My_Label_2 = ttkb.Label(text = "Ariel 15",font = ('Ariel',15) ).place(x=10,y=40)
My_Label_3 = ttkb.Label(text = "Times New Roman 15",font = ('Times New Roman',15)).place(x=10,y=80)
My_Label_4 = ttkb.Label(text = "Comic Sans MS 15",font = ('Comic Sans MS',15) ).place(x=10,y=120)
My_Label_5 = ttkb.Label(text = "Courier New 15",font = ('Courier New',15) ).place(x=10,y=160)
root.mainloop()
You can also use built in styles using bootstyle keyword.
import ttkbootstrap as ttkb
root = ttkb.Window(themename = 'litera')
root.geometry('400x200') # widthxheight
My_Label_1 = ttkb.Label(text = "Helvetica 15",bootstyle = 'primary',font = ('Helvetica',15) ).place(x=10,y=10)
My_Label_2 = ttkb.Label(text = "Ariel 15",bootstyle = 'warning',font = ('Ariel',15) ).place(x=10,y=40)
My_Label_3 = ttkb.Label(text = "Times New Roman 15",bootstyle = 'danger' ,font = ('Times New Roman',15)).place(x=10,y=80)
My_Label_4 = ttkb.Label(text = "Comic Sans MS 15",bootstyle = 'success' ,font = ('Comic Sans MS',15) ).place(x=10,y=120)
My_Label_5 = ttkb.Label(text = "Courier New 15",bootstyle = 'dark' ,font = ('Courier New',15) ).place(x=10,y=160)
root.mainloop()
Creating and Using Buttons in tkinter/ttkbootstrap
Button can be created using the following command.
button_1 = ttkb.Button(text = 'Click Me',command = button_1_handler)
To make the button do something we have to define a handler function and give its name to the command keyword argument.
def button_1_handler():
print('You Clicked Me')
So when you click the button button_1_handler() will be called and the statements inside it will run.Here it will just print amethod to the command line.
Full code below.
#Python tkinter/ttkbootstrap code for Creating and Using Buttons
import ttkbootstrap as ttkb
def button_1_handler():
print('You Clicked Me')
root = ttkb.Window(themename = 'litera')
root.geometry('400x200') # widthxheight
#create button
button_1 = ttkb.Button(text = 'Click Me',command = button_1_handler)
button_1.place(x=20,y=20)
root.mainloop()
Output of running the code.
Creating and Using Entry Box Widget in tkinter/ttkbootstrap
Entry box is a tkinter/ttkboostrap widget that is used to get input from the user.
You can create an entry widget by
My_Entry = ttkb.Entry()
this will create an entry box to which you can write text or numbers.
The entered data can be retrieved using the .get() method.
Entered_data = My_Entry.get()
You can put the .get() method inside a button handler to get the entered data when you press a button as shown below.
# ttkbootstrap Entry Widget
import ttkbootstrap as ttkb
def button_1_handler():
print(f'You Typed in {My_Entry.get()}')
root = ttkb.Window(themename = 'superhero') # theme = superhero
root.geometry('350x150')
#Create Entry Widget
My_Entry = ttkb.Entry()
My_Entry.insert(0,'Enter some data')
My_Entry.pack(pady = 20)
#Create Button
button_1 = ttkb.Button(text = 'Click Me',command = button_1_handler)
button_1.pack()
root.mainloop()
You can print a default text into the entry box to prompt the user to do some thing.
My_Entry.insert(0,'Enter some data')
On running the code ,you can see the value entered printed to command line when you press the button.
Creating and Using Drop Down Combo boxes in tkinter/ttkbootstrap
Drop down combo boxes are used to present users with a list of options from which they can select one or more items for example baud rate for serial communication or serial ports. You can use the Combobox class in ttkbootstrap to create drop down comboxes.
At first we have to create a list of items that are used to populate the drop down menu.
options = ['1200','2400','4800','9600'] #create Dropdown options
then we create the Combobox and place it inside the window using the .pack() method. You can also use .place().
You have to pass your drop down items list to the the keyword argument values
#create Combobox
my_combo = ttkb.Combobox(values = options) # Pass options list to combobox
my_combo.pack(pady = 50) # pady = 50,place it 50 units from top
when the user selects an item from combobox, the combo box will generate the '<<ComboboxSelected>>' virtual event. To handle this event ,we have to bind the combobox to a handler function.
my_combo.bind('<<ComboboxSelected>>',combobox_selected_handler) # bind the combobox
so when the user selects an item, combobox_selected_handler() function will be called and you can get the selected value using the my_combo.get() method.
def combobox_selected_handler(e):
print(e) #prints the virtual event
print(f'You selected {my_combo.get()}') #my_combo.get() get the selected value
Full code below
#Python tkinter/ttkbootstrap code for Creating and Using Drop Down Combo boxes
import ttkbootstrap as ttkb
options = ['1200','2400','4800','9600'] #create Dropdown options
def combobox_selected_handler(e):
print(e)
print(f'You selected {my_combo.get()}')
root = ttkb.Window(themename = 'litera')
root.geometry('400x200') # widthxheight
#create Combobox
my_combo = ttkb.Combobox(values = options)
my_combo.pack(pady =50)
my_combo.current(3)#set the default value on combobox
my_combo.bind('<<ComboboxSelected>>',combobox_selected_handler)#bind the combobox
root.mainloop()
Output of the code
Creating and Using Scrollable Text Box (ScrolledText) in tkinter/ttkbootstrap
ScrolledText is a multiline textbox available in kinter/ttkbootstrap with vertical and horizontal scrollbars.
To use the ScrolledText box we need to import the required classes from tkinter/ttkbootstrap.
from tkinter import *
from ttkbootstrap.scrolled import ScrolledText # import the scrolled text box
# ttkbootstrap.scrolled.ScrolledText
now you can create the text box
my_text = ScrolledText(root,height = 10,width = 200,wrap = WORD,autohide = True)
my_text.pack(pady = 20,padx =20)
Full code
import ttkbootstrap as ttkb
from tkinter import *
from ttkbootstrap.scrolled import ScrolledText # import the scrolled text box
# ttkbootstrap.scrolled.ScrolledText
root = ttkb.Window(themename = 'litera')
root.geometry('400x200') # widthxheight
my_text = ScrolledText(root,height = 10,width = 200,wrap = WORD,autohide = True)
my_text.pack(pady = 20,padx =20)
root.mainloop()
When you run the code .
You can add text to the ScrolledText text box in ttkbootstrap by
my_text.insert(END,'Helloo,type something\n')# add text
Change Font Type / Font Size
You can also change the type and size of font that appears on the ScrolledText text box in tkinter/ttkbootstrap.
# Define the font family and font size
font_family = 'Comic Sans MS'
font_size = 25
my_text = ScrolledText(root,height = 10,width = 100,wrap = WORD,autohide = True,font=(font_family, font_size))
my_text.insert(END,f'Helloo World in Comic Sans \n')# add text
Read the input text from ScrolledText box
You can also read the text written inside the ScrolledText box and use it as a input entry box, this helpful when you have to take in a large volume of text .
my_text = ScrolledText(root,height = 10,width = 100,wrap = WORD,autohide = True)
text = my_text.get('1.0',END) #get all the text from the ScrolledText widget
print(text)
The first part, '1.0' means that the input should be read from line one, character zero (ie: the very first character).
END is an imported constant which is set to the string "end".
The END part means to read until the end of the text box is reached.
The only issue with this is that it actually adds a newline to our input. So, in order to fix it we should change END to end-1c.
The -1c deletes 1 character, while -2c would mean delete two characters, and so on.
Here is a an example of how it works.
#read text from ScrolledText
from tkinter import *
import ttkbootstrap as ttkb
from ttkbootstrap.scrolled import ScrolledText
import tkinter as tk
def button_1_handler():
text = my_text.get('1.0',END) #get all the text from the ScrolledText widget
print(text)
root = ttkb.Window(themename = 'superhero') # theme = superhero
root.geometry('800x500')
my_text = ScrolledText(root,height = 10,width = 100,wrap = WORD,autohide = True)
my_text.pack(pady = 20)
#create button
button_1 = ttkb.Button(text = 'Read All Text',command = button_1_handler).pack(pady = 20)
root.mainloop()
when you press the button ,the program reads all text entered in ScrolledText box and prints it on the command line.
Displaying images on tkinter /ttkbootstrap Window
Tags
- Log in to post comments