How to Create Desktop Application Using Python

To make any project user-friendly you must have an Application whether it is a Web app or a PC App. In this tutorial, we will learn how to create desktop application using python.

Can python be used for desktop applications? Yes, there are various libraries in Python, but Tkinter is one of the simplest. So, we will be using this library to develop a simple desktop application in python.

Before we start building a desktop application I am assuming you have some basic knowledge of Python. Because in this tutorial I am not going to cover the basics of Python.

Why Tkinter?

In this tutorial, I am going to use Tkinter library to create a desktop application using Python. But Tkinter is not the only library. Other GUI frameworks are available in Python to create applications like:

Tkinter is my preferred framework because it is simple and lightweight. It is a simple framework that is best suited for beginners. However, if you want to explore more, you can learn about other frameworks.

Create Simple Desktop Application in Python

Okay now, let’s try to develop a simple desktop application using the Tkinter library of Python.

What do we want to achieve with this PC App?

Before starting coding let’s understand what we want to achieve from this Windows App. I mean what kind of functionality our App should handle?

  • I want the Application to handle two buttons
  • If we click a button it should show which button we clicked in text format
  • I will make it a little bit more advanced by fetching the text (instead of hardcoded text) from a database

Why Buttons?

I believe, to learn any framework to build an application (whether it is a web app or desktop app), if you know how to handle button activity, you almost learned 90% basics of that framework.

With that being said let’s now make a simple Windows software using Python. Let me break the entire code into some steps to explain better.

Step1: Install Tkinter Library

First, we need to install Tkinter library. To do this use below command:

pip install tk

Step2: Import Library

In order to use a library in Python, we must import it into our code. So, let’s import Tkinter as tk. Why do we import tkinter as tk? It is for your convenience so that we can use tk instead of Tkinter whenever it is required.

import tkinter as tk

Step3: Create Software Window

Next, we need to create a window for our App. This can be done by using the Tk() method of Tkinter object. Let’s do that.

# Create window Tkinter
window = tk.Tk()

Step4: Naming title to the window

We now have a window for our desktop app. Let’s give this window a name. We can accomplish this by using the title() method of Tkinter. I am giving the title of my demo application as “Simple Windows App”.

window.title(" Simple Windows App ")

Step5: Define Window size in Tkinter

Let’s now define the geometry of our application window. This is the screen size of our app window. We can define our app window size using geometry() method of Tkinter.

Now there are four ways to define screen window size in Tkinter.

Method 1: Default Window size

If you are going with the default configuration, you no need to specify geometry. In that case, when you run the application, you’ll notice that the Tkinter window appears in the top-left position of the screen and its size is small.

default geometry method in Tkinter to create desktop application using python
Method 2: Fixed Window Size

In this configuration, you can define a fixed size of your app window. To do this you just need to pass desired pixel values into the geometry() function. In this case, I am using width as 700 and height as 500 pixels.

window.geometry("700x500")
Fixed Window Size Tkinter python
Method 3: Full-Screen Window using attributes() function

This type of configuration will allow you to create a full-screen window in Tkinter for creating GUI applications in Python. To do that we need to use the attributes() method of Tkinter and set the parameter ‘-fullscreen’ and True for setting the size of our window to fullscreen and to False otherwise.

window.attributes('-fullscreen', True)

Output Screen

How to Create Full Screen Window in Tkinter

Disadvantage: It will show an output Tkinter WINDOW with no toolbar. Thus you can not select any other software. This disadvantage can be solved by the next method.

Also Read:  Integrate Plotly Dash in Django
Method 4: Tkinter Window Screen above the Toolbar

By this technique, we can get a Tkinter output window with the toolbar above.

width = window.winfo_screenwidth()               
height = window.winfo_screenheight()               
window.geometry("%dx%d" % (width, height))

Output Window

Tkinter Window Screen above the Toolbar
Method 5: Maximized Window using state() function

By this method, you can maximize the window and make it fullscreen. To do that, we need to use state() function of Tkinter python and pass ‘zoomed’ parameter string into it.

window.state('zoomed')

Both method 4 and method 5 are almost same. In method 4 you can observe the window is not completely fullscreen, there is some gap. On the other hand, using state() method you will get a truly fullscreen window above the toolbar.

I hope at this point you are clear about which one to choose for your application. For this tutorial, I am going to use fixed window using geometry() the method. Okay, now let’s move on to the next step to build a desktop application in python.

Step6: Create a Label in Tkinter

As I said our application should display which button is clicked. To display text we need to add a label widget in our application. The below code is to do that.

# Create a label widget in Tkinter
label = tk.Label(window, text="Click the Button to update this Text",
font=('Calibri 15 bold'))
label.pack(pady=20)

Here in this code:

  • paddy is nothing but padding. The number of pixels to pad (distance) widget, horizontally and vertically. Basically, this represents the position of label in our software window.

Now there are lots of other fonts available you can choose for text labels in Tkinter. To get the list of fonts in Tkinter run the below code.

# python font name list for Tkinter application
from tkinter import Tk, font
root = Tk()
font.families()

Sample output:

'System',
 '8514oem',
 'Fixedsys',
 'Terminal',
 'Modern',
 'Roman',
 'Script',
 'Courier',
 'MS Serif',
 'MS Sans Serif'

Step7: Create a function to update Lable text

In this step, we need to define two functions for two buttons. If we click the 1st button it should display “You clicked first button” and same for the 2nd button “You clicked second button

# Function to update the label text for first button click in Tkinter
def on_click_btn1():
    label["text"] = "You clicked first button"
    
# Function to update the label text for second button click in Tkinter
def on_click_btn2():
    label["text"] = "You clicked second button"

Step8: Create Button Activity

In this step, we will add to buttons into our application window and define activity of each button.

# Create 1st button to update the label widget
btn1 = tk.Button(window, text="Button1", command=on_click_btn1)
btn1.pack(pady=20)

# Create 2nd button to update the label widget
btn2 = tk.Button(window, text="Button2", command=on_click_btn2)
btn2.pack(pady=40)

Here in this code, we are passing the corresponding onclick function (on_click_btn1, on_click_btn2) to each button as a “command” parameter.

Step9: Run mainloop()

At this point we are done with our application, we just need to run the mainloop() method to see the application live. It is the main program that will execute everything that we have written above. So let’s run it.

window.mainloop()

That’s it. You successfully created a Desktop Application Using Python which should be up and running in your windows system right now.

Also Read:  Getting Started with Django with Python - Easy Tutorial

Note: In this tutorial, I covered the basics of desktop application development. If you’re serious about learning more, I recommend the Udemy course: GUI Development with Python and Tkinter.

Full Code

I spoke about lots of things to just make a simple desktop application in Python. Let me now consolidate everything and make a final code for you.

# ---------Full code to create a software application with python ---------------

# Import library
import tkinter as tk

# Create window Tkinter
window = tk.Tk()

# Name our Tkinter application title
window.title(" Simple Windows App ")

# Define window size in Tkinter python
window.geometry("700x500")

# Create a label widget in Tkinter
label = tk.Label(window, text="Click the Button to update this Text",
font=('Calibri 15 bold'))
label.pack(pady=20)

# Function to update the label text for first button click in Tkinter
def on_click_btn1():
    label["text"] = "You clicked first button"
    
# Function to update the label text for second button click in Tkinter
def on_click_btn2():
    label["text"] = "You clicked second button"
    
# Create 1st button to update the label widget
btn1 = tk.Button(window, text="Button1", command=on_click_btn1)
btn1.pack(pady=20)

# Create 2nd button to update the label widget
btn2 = tk.Button(window, text="Button2", command=on_click_btn2)
btn2.pack(pady=40)

# Run main loop
window.mainloop()

Connect Desktop App with Database

Now I will make our desktop application (made using Python) a little bit advanced. Instead of showing hardcoded text (“You clicked first button” or “You clicked second button”), I want to display some result from a database.

To keep this tutorial simple, I am going to use SQLite database in Python. Because it is simple to use and you can implement it very fast.

Okay let’s create a separate Python file. In this Python file we will create a SQLite database, then create a table and insert some values in that table. Later we will fetch this table value (created in the below code) from our Python based desktop application. Below is the code to do those.

# Create SQLite Database
import sqlite3

# Connecting to sqlite
conn = sqlite3.connect('test.db')

# cursor object
cursor = conn.cursor()
  
# Creating table
table = """ CREATE TABLE employee (
            employee_id INTEGER PRIMARY KEY,
            first_name TEXT NOT NULL,
            Last_Name TEXT NOT NULL,
            age INTEGER,
            position TEXT
        ); """
 
cursor.execute(table)

# Insert Multiple rows
emp_list = [
    ('Ritu', 'Sinha', 28, 'Software Engineer'),
    ('Ram', 'Pal', 28, 'Sr. Software Engineer')
]
 
cursor.executemany("INSERT INTO employee (first_name, last_name, age, position) VALUES (?, ?, ?, ?)",emp_list)

# Query Data
cursor.execute("SELECT * FROM employee")
rows = cursor.fetchall()
 
for row in rows:
    print(row)
Output: 
(1, 'Ritu', 'Sinha', 28, 'Software Engineer')
(2, 'Ram', 'Pal', 28, 'Sr. Software Engineer')

In the above code, I am creating a table named “employee” inside “test.db” SQLite database. Then inserting two rows to that table. If you have any difficulty understanding this code, I will recommend you to read this article: SQLite Python Tutorial with Examples.

Okay, so our database is ready. Now let’s fetch that employee information to our desktop application.

What I want to do? I want our application to show employee information once we click a button. For example, If we click the first button it should show first row of the table (from database). Similarly, if we click the second button second row will be displayed.

Fetch Data from Database

To do this, we just need to add few lines of Python code to our desktop application. First we need to fetch row data from the SQLite database. Below is the code to do this:

# Get Databse value
cursor.execute("SELECT * FROM employee")
rows = cursor.fetchall()  # Fetch all rows into a list

# First row data
first_row = rows[0]
# Second row data
second_row = rows[1]

In the above code, first two lines is to fetch all rows from our SQLite database. Last two lines to fetch first and second row from the “employee” table. If you are new to database, you can use LLM to convert natural tex to SQL query.

Also Read:  Build Question Answering API with Flask and Python

Update Button Click Function

Now the second and last modification we need to make in our desktop app Python code, is change the button click function.

# Function to update the label text for first button click in Tkinter
def on_click_btn1():
    label["text"] = "You clicked first button\n" + "EMP Details: \n" + str(first_row)
     
# Function to update the label text for second button click in Tkinter
def on_click_btn2():
    label["text"] = "You clicked second button\n" + "EMP Details: \n" + str(second_row)

Here, we just need to change the output label text. Instead of hardcoded text we need to pass the data we fetched from SQLite database. I used “\n” to show texts in the next line. You can play with different string manipulation techniques. That’s it. We are done with database integration to our desktop application. Below is the full updated code.

Full Updated Code:

import tkinter as tk

# Create window Tkinter
window = tk.Tk()

window.title(" Simple Windows App ")

window.geometry("700x500")

# Create a label widget in Tkinter
label = tk.Label(window, text="Click the Button to update this Text",
font=('Calibri 15 bold'))
label.pack(pady=20)

# Get Databse value
cursor.execute("SELECT * FROM employee")
rows = cursor.fetchall()  # Fetch all rows into a list

# First row data
first_row = rows[0]
# Second row data
second_row = rows[1]

# Function to update the label text for first button click in Tkinter
def on_click_btn1():
    label["text"] = "You clicked first button\n" + "EMP Details: \n" + str(first_row)
     
# Function to update the label text for second button click in Tkinter
def on_click_btn2():
    label["text"] = "You clicked second button\n" + "EMP Details: \n" + str(second_row)
    
    
# Create 1st button to update the label widget
btn1 = tk.Button(window, text="Button1", command=on_click_btn1)
btn1.pack(pady=20)
 
# Create 2nd button to update the label widget
btn2 = tk.Button(window, text="Button2", command=on_click_btn2)
btn2.pack(pady=40)

window.mainloop()

Take Away

Making desktop applications is simple, especially when you code in Python. Tkinter can also be used to create advanced pc apps that can be useful in real-world situations.

Some Simple Web App Python Projects You may also read:

In this tutorial, I covered the basics of desktop application development with SQLite database integration. If you’re serious about learning more, I recommend the Udemy course: GUI Development with Python and Tkinter.

I hope this article was helpful to learn how to create desktop applications using Python. If you have any questions or suggestions regarding this tutorial, let me know those in the comment section below.

Similar Read:

3 thoughts on “How to Create Desktop Application Using Python”

Leave a comment