How to package a Tkinter program to share with people?


Tkinter is a cross-platform tk GUI toolkit based on Python library which is used to create and develop GUI-based applications. Tkinter application can be bundled in an executable or runnable file which enables the application to run without using Python interpreter or IDLE. The need for bundling an application becomes a priority when the user wants to share the application with other people without sharing the piece of code.

Python has a variety of modules and extensions that gives access to the user to convert a running application into an executable, portable file. Each file runs on a different platform; thus, to make it accessible for all the operating systems, Python provides packages for Windows, MacOS, or Linux-based operating systems.

Here, we will use the Pyinstaller package in Python to bundle the application into an executable file. In order to install Pyinstaller, you can use the following command −

pip install pyinstaller

Once installed, we can follow the steps to convert a Python Script File (contains a Tkinter application file) to an Executable file.

  • Install pyinstaller using pip install pyinstaller in Windows operating system. Now, type the following command and press Enter.

pyinstaller --onefile -w filename
  • Check the location of the file (script file) and you will find a dist folder which contains the executable file in it.

  • When we run the file, it will display the window of the tkinter application.

Example

In this example, we will create an application that will ask the user to enter a name and it will greet the user with their name.

# Import the required Libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame
win =Tk()

# Set the geometry of tkinter frame
win.geometry("750x250")

# Define a function to show a message
def myclick():
   message="Hello "+ entry.get()
   label=Label(frame, text=message, font=('Times New Roman', 14, 'italic'))
   entry.delete(0, 'end')
   label.pack(pady=30)

# Creates a Frame
frame =LabelFrame(win, width=400, height=180, bd=5)
frame.pack()

# Stop the frame from propagating the widget to be shrink or fit
frame.pack_propagate(False)

# Create an Entry widget in the Frame
entry =ttk.Entry(frame, width=40)
entry.insert(INSERT, "Enter Your Name")
entry.pack()

# Create a Button
ttk.Button(win, text="Click", command=myclick).pack(pady=20)

win.mainloop()

Output

Now, run the following command to convert the given code into an executable file.

pyinstaller --onefile -w filename

It will affect the directory (dist folder) where all the executable files will be placed automatically.

When we run the exe file, it will display a window that contains an Entry widget. If we click the "Click" button, it will display a greeting message on the screen.

Updated on: 18-Jun-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements