Tkinter: Python GUI Toolkit

Introduction to Tkinter

Tkinter
Tkinter

Tkinter is Python most favourite widely used GUI library for Python developers. Alongside Tkinter, Custom Tkinter was made, heavily based on Tkinter but with a focus on the modern needs of GUI Development, Custom Tkinter has seen a rapid rise in popularity. However, despite their easy syntax, Tkinter and Custom Tkinter can be just as difficult for professional sized GUIs as other libraries. With each Tkinter element needing a couple lines of code, project can easily become thousands of lines of code for just the GUI. The Tkinter GUI Designer removes the need for any code when creating GUIs, our simple drag and drop interface lets users add, customise and readjust GUI elements in a matter of time, saving enormous amounts of work. With some much time saved, developers can run through additional iteration of their GUI, allowing them to create the perfect GUI for their needs. By generating the Tkinter code for you, Tkinter Designer save you from the tedious debugging and errors of writing such repetitive and boring code, creating a stress free and efficient atmosphere.

Tkinter GUI Designer Example
Tkinter GUI Designer Example

There are four options on how to use Tkinter

  • Classical Tkinter
  • Custom Tkinter
  • Drag and Drop Tkinter GUI Designer
  • Using Tkinter GUI Designer alongside AI and LLMs

Classical Tkinter

Tkinter is the most widely used Python GUI Library, known for its ease of use, cross- compatibility and trustworthiness. It is the only GUI library which is part of Tkinter Standard library and has long been seen as the go to Python GUI library, with all popular libraries supporting Tkinter with the most notable being Matplotlib, Seaborn and more.

Drag and Drop Tkinter Dark
Drag and Drop Tkinter Dark

Custom Tkinter

Custom Tkinter is modern take on the iconic Tkinter library, with a focus on an updated and material-style look, Custom Tkinter brings a fresh a clean look to your GUI while retain Tkinter famous ease of use and cross-compatibility. With a rapidly growing community, Python has taken to Custom Tkinter in record time.

Light Mode Custom Tkinter Task Management GUI
Light Mode Custom Tkinter Task Management GUI

Drag and Drop Tkinter GUI Designer

Using the Tkinter
Using the Tkinter

The Tkinter GUI Designer is an intuitive drag and drop GUI Designer which specialises in generating code for professional GUIs in a matter of minutes. It removes all the tedious and monotonous working of creating GUIs and allows you to focus on your UI design without worrying about mistakes or wasting time. Our drag and drop GUI Designer generates the Tkinter and Custom Tkinter code and it is part of our MD Python GUI Designer package.

Using Tkinter GUI Designer alongside AI and LLMs

The Tkinter code generated has also been specifically optimized to be used along all the most used LLMs such as ChatGPT, Claude, Gemini and more. Whether you just want to remove the hassle of coding all the repetitive and boring parts of your backend or you want LLMs to generate your whole backend, we ensure that the Tkinter code is readable for everyone and optimised for LLMs. This gives you the option to create whole application without having to write a single line of code or writing only the code that matters.

Creating the actual Tkinter GUI is solved by the GUI Designer, however, the functionality of the Tkinter GUI is solved by the AI code generator. Now, users with little to none experience, can both create and implement Tkinter GUIs with no lines of code.

Why Tkinter

The simple and fast way to create GUI in Python Simplicity is based on Tkinter object-oriented code structure. The classical approach of importing the Tkinter module creates a root container window and placing the Tkinter widget into the container. This widget has oven events that trigger the specific property function.

Simplicity of Tkinter

Tkinter simplicity is by adding GUI elements which are Tkinter widgets to the Tkinter container.  Tkinter widgets are easily customizes. Naturally, these Tkinter widgets can be automatically generated by GUI designers giving you the benefit of resizing elements, generating error-free code, and automatically placing widgets events.

Python GUI using Tkinter

This intuitive interface makes it a favourite among both beginners and experienced Python developers, helping to create professional-level applications efficiently without the need for costly resources.

Tkinter Widgets

Tkinter widgets include Label, Button, Text entry, Text Box, Multiline Text, List Box, Check Button, Radio Button and Frame. More advanced widgets include Menu Bar, Canvas Widget, Dialogue box, and Bind events handlers. For more information about widgets in Tkinter, have a look below at the Learn Tkinter programming section.

Widgets in Tkinter are elements within a GUI container that are created in order to interact with users and represent certain states for the user. Tkinter widgets are organised and set by the user.

Multiplatform Tkinter Python GUI

With Tkinter, you can develop a single codebase that runs on various desktop platforms like Windows, Linux, iOS, and Raspberry Pi. This allows you to build lightweight, memory-efficient UIs without extensive optimization efforts. The similarity in appearance of Tkinter apps on Windows and Raspberry Pi demonstrates this capability.

Windows and Raspberry Pi Python GUIs Side by Side
Windows and Raspberry Pi Python GUIs Side by Side

The Tkinter UI Designer includes over 20 customizable widgets and a straightforward drag-and-drop interface for resizing and rearranging elements. This makes it an excellent choice for creating beautiful Python UIs without the need to learn a different programming language. The Tkinter GUI Designer enables you to bring complex ideas to life effortlessly, all without writing code.

Specialized Tkinter Python GUI IDE

When using the Custom Tkinter GUI Designer your code will be generated inside of MatDeck’s Python IDE which offer you professional features which will save you time, stress and money. The most popular and powerful feature is code-completion which offer relevant suggestions to speed up you’re typing and eliminate the chance of mistakes.

The Tkinter Python IDE is perfect for managing python modules and libraries as no function or CLIs are needed. With Python Settings, you can Install, Update and List Python modules/libraries by simply entering the name or clicking a button.

Install, Update and List Python Modules
Install, Update and List Python Modules

A Python debugger is also embedded inside our dedicated Tkinter Python IDE meaning that you can get simple suggestions to debug your code as quickly as possible and get your code to its best without any confusing error messages.

This image has an empty alt attribute; its file name is tkinter-gui-designer-generating-code-in-tkinter-ide.png
Tkinter GUI Designer generating code in Tkinter IDE

Breakpoints are a fantastical feature that allows you run selected parts of your code to better debug logic error in your code. They allow you to see the exact path that you program will take. This includes which if, else if and else statements you code will enter as well as how it interacts with for and while loops.

Python Tkinter
Python Tkinter

Learn Tkinter programming

The easiest method to learn how to use the Tkinter library is through creating and analysing examples. Comments used throughout a Tkinter GUI can provide users with insight on what various commands and code blocks do.

As we can see in the simple example below, we used the Tkinter GUI Designer to create a simple, useful and professional GUI. In this example we use Tkinter Labels, Buttons, Combo boxes and Text entries, all of this was added to canvas and then resized, moved and customized to fit the user’s vision.

Tkinter GUI
Tkinter GUITkinter GUI

As you can see from the Tkinter code and Tkinter GUI below, widget definitions and functions are all created by our Tkinter GUI Designer, you can then move the widgets even more, change widget sizing, color as well as font all without needing to write a single line of code.

from tkinter import *

from tkinter.ttk import Progressbar

from tkinter.ttk import Combobox

from tkinter.ttk import Notebook

from tkinter.ttk import Treeview

from PIL import Image, ImageTk

import tkinter.font

from matdeck.tkinter.COMWidget import COM_Widget

from matdeck.tkinter.TCPWidget import TCP_Widget

import psycopg2 # For PostgreSQL

import pymysql # For MySQL

import pyodbc # For Microsoft SQL Server

import cx_Oracle # For Oracle Database

import sqlite3 # For SQLite

class Widget1():

 def __init__(self, parent):

 self.gui(parent)

 def gui(self, parent):

 if parent == 0:

 self.w1 = Tk()

 self.w1.geometry('560x340')

 else:

 self.w1 = Frame(parent)

 self.w1.place(x = 0, y = 0, width = 560, height = 340)

 #Creating the first label with width 200 and height 30 and place at coordinates (30,90)

 self.label1 = Label(self.w1, text = "Server Type:", anchor='w', font = tkinter.font.Font(family = "Arial", size = 12, weight = "bold"), cursor = "arrow", state = "normal")

 self.label1.place(x = 30, y = 90, width = 200, height = 30)

#Creating the second label with width 200 and height 30 and place at coordinates (30,130)

 self.label2 = Label(self.w1, text = "Server Name:", anchor='w', font = tkinter.font.Font(family = "Arial", size = 12, weight = "bold"), cursor = "arrow", state = "normal")

 self.label2.place(x = 30, y = 130, width = 200, height = 30)

 #Creating the third label with width 200 and height 30 and place at coordinates (30,170)

 self.label3 = Label(self.w1, text = "Authentication:", anchor='w', font = tkinter.font.Font(family = "Arial", size = 12, weight = "bold"), cursor = "arrow", state = "normal")

 self.label3.place(x = 30, y = 170, width = 200, height = 30)

 #Creating the fourth label with width 200 and height 30 and place at coordinates (30,210)

 self.label4 = Label(self.w1, text = "Username:", anchor='w', font = tkinter.font.Font(family = "Arial", size = 12, weight = "bold"), cursor = "arrow", state = "normal")

 self.label4.place(x = 30, y = 210, width = 200, height = 30)

 #Creating the fifth label with width 200 and height 30 and place at coordinates (30,250)

 self.label5 = Label(self.w1, text = "Password:", anchor='w', font = tkinter.font.Font(family = "Arial", size = 12, weight = "bold"), cursor = "arrow", state = "normal")

 self.label5.place(x = 30, y = 250, width = 200, height = 30)

 #Creating the first line text box with width 300 and height 25 and place at coordinates (230,133)

 self.ltext1 = Entry(self.w1, font = tkinter.font.Font(family = "Calibri", size = 9), state = "normal")

 self.ltext1.place(x = 230, y = 133, width = 300, height = 25)

 #Creating the second line text box with width 300 and height 25 and place at coordinates (230,173)

 self.ltext2 = Entry(self.w1, font = tkinter.font.Font(family = "Calibri", size = 9), state = "normal")

 self.ltext2.place(x = 230, y = 173, width = 300, height = 25)

 #Creating the third line text box with width 300 and height 25 and place at coordinates (230,213)

 self.ltext3 = Entry(self.w1, font = tkinter.font.Font(family = "Calibri", size = 9), state = "normal")

 self.ltext3.place(x = 230, y = 213, width = 300, height = 25)

 #Creating the fourth line text box with width 300 and height 25 and place at coordinates (230,253)

 self.ltext4 = Entry(self.w1, font = tkinter.font.Font(family = "Calibri", size = 9), state = "normal")

 self.ltext4.place(x = 230, y = 253, width = 300, height = 25)

 #Creating the first combobox with width 300 and height 25 and place at coordinates (230,93)

 self.combo1 = Combobox(self.w1, font = tkinter.font.Font(family = "Arial", size = 12, weight = "bold"), cursor = "arrow", state = "normal")

 self.combo1.place(x = 230, y = 93, width = 300, height = 25)

 #Populating the combobox with the following options

 self.combo1['values'] = ("Microsoft SQL Server", "MySQL", "PostgreSQL", "SQLite", "Oracle Database", "SQL Server on Azure", "Amazon RDS")

 self.combo1.current(0)

 #Creating the first button with width 110 and height 25 and place at coordinates (420,293)

 self.button1 = Button(self.w1, text = "Connect", font = tkinter.font.Font(family = "Arial", size = 12, weight = "bold"), cursor = "arrow", state = "normal")

 self.button1.place(x = 420, y = 293, width = 110, height = 25)

 self.button1['command'] = self.on_connect

 #Creating the title label with width 470 and height 72 and place at coordinates (45,10)

 self.label6 = Label(self.w1, text = "Connect to an SQL Database", anchor='w', font = tkinter.font.Font(family = "Arial", size = 26, weight = "bold"), cursor = "arrow", state = "normal")

 self.label6.place(x = 45, y = 10, width = 470, height = 72)

 def on_connect(self):

 #Getting user inputs

 server_type = self.combo1.get()

 server_name = self.ltext1.get()

 username = self.ltext3.get()

 password = self.ltext4.get()

 #Validation: Ensure all fields are filled

 if not server_name or not username or not password:

 messagebox.showerror("Input Error", "Please fill in all fields.")

 return

 #Mapping server types to connection logic

 connection_map = {

 "Microsoft SQL Server": lambda: pyodbc.connect(f'DRIVER={{SQL Server}};SERVER={server_name};UID={username};PWD={password}'),

 "MySQL": lambda: pymysql.connect(host=server_name, user=username, password=password),

 "PostgreSQL": lambda: psycopg2.connect(host=server_name, user=username, password=password),

 "SQLite": lambda: sqlite3.connect(server_name), # SQLite uses the file path for the server name

 "Oracle Database": lambda: cx_Oracle.connect(username, password, server_name),

 "SQL Server on Azure": lambda: pyodbc.connect(f'DRIVER={{ODBC Driver 17 for SQL Server}};SERVER={server_name}.database.windows.net;DATABASE=master;UID={username};PWD={password}'),

 "Amazon RDS": lambda: pyodbc.connect(f'DRIVER={{MySQL ODBC 8.0 Driver}};SERVER={server_name};DATABASE=master;USER={username};PASSWORD={password}')

 }

 try:

 #Attempting the connection using the corresponding lambda function

 connection_map[server_type]()

 messagebox.showinfo("Success", f"Successfully connected to {server_type}.")

 except Exception as e:

 messagebox.showerror("Connection Error", f"Failed to connect: {str(e)}")

if __name__ == '__main__':

 a = Widget1(0)

 a.w1.mainloop()

You can see just how useful the Tkinter GUI Designer is above, with all the Tkinter code being generated for you, this is more than three quarters of the code. All that’s let is a simple event function which can easily done by LLMs such as ChatGPT, CoPilot and Claude. The Tkinter GUI can still be easily customizable as the code in the event function is saved while you can make all the changes you would like to your GUI.

Tkinter Tutorial

Tkinter has established itself as a cornerstone library for graphical user interface (GUI) development in Python, widely adopted across various industries for its ability to transform complex interface design into manageable, straightforward code. While Tkinter already simplifies GUI creation, innovative tools like the MatDeck Tkinter GUI Designer have emerged to further streamline the development process, pushing the boundaries of rapid interface development.

The MatDeck Tkinter GUI Designer represents a significant leap forward in GUI development methodologies. By introducing a comprehensive, interactive toolbox, this solution fundamentally transforms how developers and designers approach interface creation. Unlike traditional coding approaches that require manual widget placement and configuration, this Tkinter designer provides an intuitive, drag-and-drop environment where customizable GUI elements can be effortlessly positioned and styled.

Naturally being a Python library, Tkinter draws the most use from programmers and developers. However this barrier to use, is reduced by MatDeck’s GUI Designer and AI code generation. Here, MatDeck’s GUI Designer provides the framework in order to generate Tkinter GUIs through customisable Drag and Dop elements.

In terms of Python GUI creation and development, Tkinter presents itself as a smart option due to ubiquity among developers, cross-platform compatibility, and inherent simplicity. With new emerging technologies such as MatDeck’s Tkinter GUI Designer and AI code generators has reduced the strain and experience need to create Python GUIs. However to utilise Tkinter’s advantages in a traditional coding environment requires knowledge of prevalent Tkinter functions and alternative Tkinter libraries and options.

The key areas of Tkinter that are useful to know can be broken down into main components, key widgets, event handling and layout managers.

Before any area of Tkinter can be approached, Tkinter must be first imported in the Python application as it is a library.

import tkinter as tk

Main Components

Once imported we can further elvove the Tkinter GUI by initiating some of the main components. The main goal at the start of a Tkinter application is to instantiate a main window to house the widgets and use a Tkinter event loop to start the GUI event loop and keep the window running.

root = tk.Tk()
root.title("Hello MatDeck")

Here, the main window has been created using Tk() and a title has been added to the window. Now to ensure that the window “Hello MatDeck” continues to loop, mainloop() is used as such below.

root.mainloop()

You can notice in the example code above that the main window that is created is stored as root and referenced by functions as such. “Root” is used as the main window serves as the basis for all the other Tkinter windows effectively making the main window the root. Now that the main components that house other Tkinter components has been created, widgets can be created.

Key Widgets

Tkinter is equipped with a plethora of varying widgets that can be implemented to create interactive applications. Standard Tkinter libraries come complete with 12 widget options varying from buttons to spinboxes. Alterations such as the Tkinter module ttk provides an added 6 widgets for use. Certain widgets are naturally used much more which is what is considered Tkinter’s key widgets. To properly utilise Tkinter without aides such as GUI Designers and AI generators, having a in-depth knowledge of Tkinter’s key widgets is recommended.

  • Label: Display text or images
  • Button: Clickable buttons with actions
  • Entry: Single-line text input
  • Text: Multi-line text input
  • Checkbutton: Checkbox for boolean selections
  • Radiobutton: Mutually exclusive selection options
  • Listbox: List of selectable items
  • Combobox: Dropdown selection (requires ttk module)

To create widgets in Tkinter they need to be addressed to the window that they will be created in. Tkinter widgets can be instantiated by using writing their name with a capital making sure to also reference the library they are being called from which in this case is Tkinter.

button = tk.Button(root, text="Click Me", command=on_button_click)

In the example above, we can see a button widget being created. From here we can see that the button widgets has 3 different parameters declared. Parameters used within Tkinter widgets can vary but most will be of the from above. The first parameter is “root”, which refers to the parent window that this widget will be deployed in. The second parameter is to declare with text will be displayed on the widget. The third parameter is the most important parameter which is used to declare the event function that is called up when the widget is interacted with. Event functions and the handling of various events within a GUI is the most crucial part of a Tkinter application in order to give it functionality. In this example, the event called upon is on_button_click which Python will automatically execute once the button is pressed. In the case of the button, the command option is used which is not available for all widgets.

It is important to note 2 aspects of the event used above. First, no parenthesis are used meaning the event receives no arguments. Secondly, the event function referenced needs to be declared first. Knowing how to create event function and interact with them is pivotal to the success of your Tkinter GUI’s functionality.

Event Handling

An event is simply categorised as actions or something occurring within a GUI. Events can include mouse clicks, key presses, and keyboard shortcuts. Event handling in Tkinter refers to what actions are declared as events and what outcome is created when an event within the GUI occurs. There are two steps to succesfuly handling events in Tkinter. Firstly, declaring and creating the event function and then binding the event function to specific widgets.

To create event functions using Tkinter we must declare the event function like all other functions that are defined in Python.

def on_button_click():

The body of the function will contain the consequential logic and actions that the developer wants to occur once the specified event occurs. In the case of our Tkinter button, we will have a simple print statement occur.

print("Button clicked!")

Now this event function can be used as a button command as such.

button = tk.Button(root, text="Click Me", command=on_button_click)

when using widgets that don’t have the command option such as the button example above, the event and the event function can be banded together through the use of bind(). Using the same approach for the button, we must first declare our event function and the logic we wish to execute.

def on_key_press(event):
print(f"Key pressed: {event.char}")

Layout Management

Layout Management is a important step in the process of creating GUIs in any language or form. For a GUI’s functionality and design to be useful and worthwhile a well thought out layout should be used. A organised layout will make both the user’s and developer’s experience simpler. In terms of Tkinter, Layout Management refers specifically to how widgets are organized and arranged within a window or container.

It is important to note that without a layout specified for widgets, they will not appear in the GUI window. Only once the layout is specified, widgets will become visible further emphasising just how important a appropriate layout is. Each layout approach has its own options that can be deployed for specific scenarios. Options and the necessary information to deploy them can be found across the web.

There are 3 types of Layout Management in Tkinter: Place, Pack and Grid.

Using the place approach is arguably the most basic option. Here, the user can specify the exact coordinates they wish to place a widget. The same cartesian coordinates X and Y are used but replaced with row and column respectively.

label.grid(row=0, column=0)

For the purpose of the example above, a lable widget was made using the Tkinter code below.

label = tk.Label(root, text="Label 1")

While being the easiest approach to implement, placing widgets creates new challenges for users. Changes to one widget will not automatically adjust other widgets leading to a much less responsive design where window resizes won’t be accounted for.

Another approach similar to place, is to pack widgets. Instead of placing single widgets on specific coordinates, this approach will place widgets sequentially in a order specified by the user. Users can organise widgets both vertically and horizontally, by default widgets are packed vertically, from the top of the window downwards.

label.pack(side="top")

Same as the example earlier, a label widget is created to illustrate the different layout approaches.

The last approach, Grid, is the most flexible option for widget layout management in Tkinter. Instead of organizing Tkinter widgets in terms of exact positions and sequences, this approach formats the Tkinter window into a grid of positions.

label.grid(row=0, column=0)