Understanding Tkinter: Python's Gateway to GUI Development


Tkinter, an integral part of Python's standard library, is a powerful tool for crafting graphical user interfaces (GUIs). This library equips developers with an array of widgets and tools necessary for building robust desktop applications, ensuring seamless functionality across various platforms like Windows, macOS, and Linux. Rooted in the Tk GUI toolkit, originally designed for the Tcl programming language, Tkinter has been adeptly adapted for Python, enhancing its versatility.

Podcast on Tkinter the Python GUI Development

How to install Tkinter Module 🔝

Tkinter comes with Python and while installing python check the tcl/tk and IDLE checkbox. To install Tkinter subsequently we have to use the command like this .
C:\Users\user name>pip install tk
Installation of Python is to be completed before installing Tkinter library . ( how to check Python installation is here. )

If you are getting error modulenotfounderror: no module named 'tkinter' then use the above steps to install Tkinter library.

What is my Tkinter Installed Version? 🔝

import tkinter
print(tkinter.TkVersion) # 8.6 

check tkinter installation 🔝

Run this command at your command prompt ( type cmd in your system.)
One small window will open showing you the details.
C:\Users\user name>python -m tkinter
Tkinter Installation & version

Show one blank window. 🔝

import tkinter as tk
my_w = tk.Tk()
my_w.geometry("500x500")  # Size of the window 
my_w.title("www.plus2net.com")  # Adding a title
my_w.mainloop()  # Keep the window open
Close window by using Esc
my_w.bind('<Escape>', lambda e:my_w.quit()) # to close. 
my_w.destroy() Close the window

geometry() 🔝

my_w.geometry("400x350+410+100")  # Size & Position
400 : width of the window
350 : Height of the window
410 : Position (opening ) of the window from left or X position
100 : Position (opening ) of the window from Top or Y position

Using height and width variables with geometry of the window. Inside our script we can use these variables.
width,height=710,710 # set the variables 
d=str(width)+"x"+str(height)
my_w.geometry(d) 
Resizing of window is possible by default, but we can manage this setting by making resizing height, width to False
my_w.resizable(width=0,height=0) # resizing of window is not allowed 
While opening we can set to full screen
my_w.state('zoomed') # default is 'normal' 
More about managing geometry

Python GUI basic window code using Tkinter library for displaying first blank window

What is mainloop() ? 🔝

The mainloop() function is what keeps a Tkinter application running and responsive. It's the heart of any Tkinter application, it handles events, user interactions, and rendering updates to the GUI. Without calling mainloop(), a Tkinter application would open a window and immediately close it, or not open it at all, since the program would reach its end without waiting for user interaction.

Check the two print commands here, after closing of the Tkinter window the last line will be printed. The line just before the last print command my_w.mainloop() will make the program wait for user interactions and will allow further execution ( below it ) once the window is closed.
import tkinter as tk
my_w = tk.Tk() # root window
my_w.geometry("400x250")  # Size of the window 

print( ' I am before mainloop ')
my_w.mainloop()  # Keep the window open
print(' I am after mainloop')
Explore how the application behaves by toggling the my_w.mainloop() line: comment it out to observe the effect, then uncomment it to see the differences in application functionality.

Change the background colour 🔝

my_w.configure(background='black')
#OR
#my_w.configure(background='#FFFF00')
To above code we will add different components.

List of widgets in Tkinter 🔝

askopenfileDialog box to show file browser & upload file from local system
askopenfileUpload and display images using file browser
ButtonAdd button with click events and style
CanvasDraw Line, Arc, Oval, Polygon ,rectangle etc
CheckbuttonRead data and manage (set or get) of a checkbutton
colors Tkinter supported colors list
colorchooseraccess the native colour picker dialog
clockDisplay time with Date
CalendarDisplay Date picker
DateEntryDisplay Drop-down Date entry
EntryAdd Text box , Single line text entry
frameGroup widgets and add separator to window
imageDisplaying icon and Images on Window
LabelAdd Label and change text & other attributes
LabelFrameGroup Widgets and add Label
ListboxRead selection , add elements to a listbox
MessageDisplaying in-process Messages
MessageBoxShow Message box and take user choice
MenuMenu with option and methods
MenubuttonDropdown menu
OptionMenuDrop down box to select one of many options
PanedWindowContainer allowing user to adjust the size by using the mouse
RadiobuttonRead data and manage (set or get) of a Radio button
ScaleUse slider to fix value
ScrollbarScrollbar options and uses
simpledialogDialog box to take user input.
StringVartk.StringVar() and trace with callback functions
SpinboxUser selection from a range of options
TextAdd Text box , Multi line text entry
ToplevelDisplay pop-up or child window from Parent

ttk : Tkinter Themed widgets 🔝

ttk, which stands for Themed Tk, is a newer addition to Tkinter that provides access to the themed widget set introduced in Tk 8.5. This module allows for the creation of widgets that can more closely match the native look and feel of a user's operating system.
import tkinter as tk
from tkinter import ttk
ttk comes with 18 widgets, twelve of which already existed in tkinter:

Button, Checkbutton, Entry, Frame, Label, LabelFrame, Menubutton, PanedWindow, Radiobutton, Scale, Scrollbar, and Spinbox.

The other six are new:
ComboboxManaging options of a dropdown Combobox
NotebookMethods and options to manage Tabs
ProgressbarDisplaying status of process with options and methods
SeparatorVertical and Horizontal separators
SizegripAdding window resizing capabilities.
TreeviewBasics of Treeview for tabular data


Layout of widgets in Tkinter window 🔝

gridOrganizes widgets in rows and columns, offering more precise control.
packSimple, arranges widgets in blocks either vertically or horizontally.
placePlaces widgets at exact x, y coordinates for precise positioning.

Handy Reference 🔝

AttributesHow to list, read or update the values
validationValidating user inputs
EventsMouse and Keyboard Events using Call back functions
config()access the access the object's attributes after its initialization

ttkbootstrap 🔝

ttkboostrap themes

MySQL 🔝

We can connect to MySQL database from Python and manage the data. Tkinter adds the GUI capability to this data handing capacity. We will learn about adding data, displaying, updating etc by using standard SQL.
Python to MySQL connection and handling data
MySQLDisplaying records from MySQL database in Tkinter window
TreeviewDisplaying records from MySQL database in Tkinter window using Treeview
DeleteDeleting selected row from MySQL table and Treeview
PaginationPagination of records from MySQL table using Treeview
PagingPagination of records of MySQL table using Tkinter window
record displayDisplaying record in a Tkinter window by taking user input as row id
record updateSelect-Edit-Update row by using Treeview
Image displayDisplaying Binary data from MySQL Blob column.
Image displayDisplaying all records with Images from MySQL Blob column.
Image addInserting uploaded image to Blob column of MySQL table
Image addAdding data to student table with Photo using Blob column of MySQL table
Image UpdateUpdating user uploaded image in MySQL Blob column
record addAdding user entered data through Tkinter window to MySQL table
LoginSystem for Login with add user and listing users with delete option
RandomDisplay Random record from MySQL or SQLite Database.
Ticket No.Generate unique string id using date after inserting record
ExerciseExercise on Tkinter and Managing MySQL database

SQlite 🔝

SQLite is a file based database with full functional capacity like any other Relational Database. Portability is the main advantage of SQLite database. Using sqlite3 library we can manage SQLite database by using Standard Query languages. By using Tkinter we can add GUI capability to manage SQLite database from Python.
Display records from SQLite table in Tkinter window

Dynamic Graphs in Tkinter GUI 🔝

Display Pandas DataFrame graphs in Tkinter

To list all available methods of any widget
l3 = tk.Label(my_w,  text='Welcome')
object_methods=[l3 for l3 in dir(tk.Label)
               if callable(getattr(tk.Label,l3))]
print(object_methods)

Download .zip file with .ipynb files
of Video Tutorials

Transparent Window 🔝

my_w.attributes('-alpha',0.5)

Time delay using after() 🔝

l1 is one Label, this code will update the text on Label l1 after 3000 millseconds ( 3 seconds ).
l1.after(3000,lambda:l1.config(fg='white',bg='white',text=''))

Creating windows EXE file from Tkinter 🔝

Developing executable desktop applications by using PyInstaller in Tkinter Python library


Install PyInstaller by using Pip install.
pip install pyinstaller
From command prompt move to the directory where your source file is there ( this is required if path is not set ) . You can run from your existing prompt also.
python3 -m PyIntaller tk-clock.py
This will create several files and directories at the same location. Your application will be inside the dist directory.

Creating single application file 🔝

python3  -m PyInstaller  --onefile --windowed  tk-clock.py

importat tips for application development 🔝

Don’t initialize any widgets inside a function. Start them from root of your script and manage the options (attributes) from inside the functions by using config() method.

Keep the common requirements like Database connection string in a common file and call them from different scripts. This helps in changing the login details in one location when you shift to different database.

If you have common logo, background colour etc. then store them inside config.py file ( can use any other name ) and call them from different scripts. Easy maintenance.

QR code generator 🔝

Generating QR code in Tkinter window



Podcast on Tkinter the Python GUI Development


Projects using Tkinter Python Tkinter Live Session at 7 PM in Hindi
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer