Welcome to Part 2 of our PySimpleGUI 2020 tutorial! In this section, we will be learning how to add a GUI "Front End" to a Command Line Interface (CLI) application. Please note that this feature is still considered experimental, so it may not be suitable for all use cases. However, it can be a great way to enhance the user experience of your command line tool.
To begin, make sure you have PySimpleGUI 2020 installed on your system. You can install it using pip:
pip install PySimpleGUI
Now, let’s get started with adding a GUI front end to your CLI application. First, create a new Python script for your CLI application. For this tutorial, let’s create a simple application that calculates the square of a number entered by the user.
# cli_app.py
def main():
number = input("Enter a number: ")
result = int(number) ** 2
print(f"The square of {number} is {result}")
if __name__ == '__main__':
main()
Now that we have our CLI application ready, let’s add a GUI front end to it using PySimpleGUI. Create a new Python script for the GUI front end:
# gui_frontend.py
import PySimpleGUI as sg
import subprocess
layout = [[sg.Text("Enter a number:"), sg.InputText(key='number')],
[sg.Button("Calculate"), sg.Button("Exit")]]
def main():
window = sg.Window('CLI App with GUI Front End', layout)
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Exit':
break
elif event == 'Calculate':
number = values['number']
process = subprocess.Popen(['python', 'cli_app.py'],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
output, _ = process.communicate(number)
sg.popup(output)
window.close()
if __name__ == '__main__':
main()
In this script, we define a simple layout for our GUI front end using PySimpleGUI. The main()
function creates a PySimpleGUI window with the layout and listens for user interactions. When the user clicks the "Calculate" button, it runs the CLI application in a subprocess and displays the output in a popup window.
To run the application, first start the GUI front end script in a terminal:
python gui_frontend.py
This will open a PySimpleGUI window where you can enter a number and click the "Calculate" button. The CLI application will be executed in the background, and the result will be displayed in a popup window.
As mentioned earlier, this feature is experimental, and there may be limitations or issues when integrating a GUI front end with a CLI application. However, it can be a useful tool for providing a more interactive user experience for your command line tools.
That’s it for Part 2 of our PySimpleGUI 2020 tutorial! Stay tuned for more tutorials on PySimpleGUI and other Python GUI frameworks. Happy coding!