Converting Tkinter program to exe file


Let us suppose that we want to create a standalone app (executable application) using tkinter. We can convert any tkinter application to an exe compatible file format using the PyInstaller package in Python.

To work with pyinstaller, first install the package in the environment by using 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 pyinstaller --onefile -w filename and press Enter.

Now, 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

main.py

In this example, we have created an application that will greet the user with their name by displaying the message on the screen.

#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()

Now, run the above command to convert the given code into an executable file. It will affect the directory (dist folder) where all executable file will be placed automatically.

Output

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: 03-May-2021

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements