Make a GUI with just ONE LINE of code using Python
Introduction
Hey there! In this post, I’m going to show you how to create various popups in Python using the PySimpleGUI library, all with just one line of code. Whether you need to ask the user to select a folder, choose a file, pick a date, or enter some text, I’ve got you covered. Plus, I’ll introduce a simple progress bar that calculates the remaining runtime of your loop. Let’s dive in!
One Line GUIs
To get started, you’ll need to install the PySimpleGUI library. You can do this by running the command pip install pysimplegui
in your command prompt or terminal. Once that’s done, you can import PySimpleGUI as sg
. Let’s kick things off with a common task: gathering a folder path from the user. Instead of hardcoding a folder path, you can prompt the user to choose one using the following line: sg.popup_get_folder("Select a folder")
This will create a window where the user can browse and select a folder. If they hit ‘OK’, the selected path will be returned as a string. If they cancel, it returns None
. Next, if you want to allow file selection, you can use: sg.popup_get_file("Select a file")
Here, you can also add additional arguments to customize the selection, such as allowing multiple file types or specific file extensions. Another useful popup is for selecting a date: sg.popup_get_date()
This brings up a calendar interface, allowing the user to navigate through months and years easily. For user input, you can use: sg.popup_get_text("Enter some text")
This creates a simple input box where users can type their text. If they cancel, it returns None
.
Practical Example
Now, to showcase the power of these popups, let’s look at a practical example. Imagine you have a Python script that needs to process Excel files in a folder. Instead of hardcoding the file paths, I’ll modify the script to ask the user for the input and output directories. Here’s how it works:
- Prompt the user to select the input folder containing Excel files.
- Prompt for the output directory where you want to save the new workbooks.
- Use a one-line progress meter to keep the user informed of the current progress.
The progress meter will provide a title and show the current index of the loop, calculating the remaining duration based on the iterations.
Bonus
As a bonus tip, you can convert your Python script into a standalone executable file using the psgcompiler
. This means users won’t need to have Python installed to run your program. After installing psgcompiler
, simply select your Python file and click convert. You’ll then have an executable ready to go!
Summary
And that’s a wrap! You’ve learned how to create various popups in Python with just one line of code, how to implement a progress meter, and even how to convert your script into an executable. These tools can significantly enhance user interaction with your applications. Thanks for reading!