Solutons Lounge

How To Create a Python GUI To Write Data to a File With PyQt5


You might think Python is only good for text-based applications and web app development but on that front you’d be wrong. For those who are interested in creating GUI apps with Python, some libraries and bindings make it possible.

One such binding is PyQT5. Last time around I walked through through the process of creating a basic GUI with this set of cross-platform C++ libraries but that app really didn’t do much beyond Hello, World.

This time, I want to demonstrate how to use PyQT5 to create a Python GUI app that accepts input from a user and then writes that input to a file. This can be helpful when you want to accept input from a user and append it to a file… all from a user-friendly GUI.

This is possible with the help of PyQT5.

Before we get into this, there are a few things we’ll want to review. I’ll do a quick recap on these points.

  • The double underscore is used for name mangling. The double pre underscore instructs the Python interpreter to rewrite the attribute name of a subclass to avoid naming conflicts.
  • We have to import a number of features from the sys library
  • The Python sys library provides access to variables and functions that interact with the Python interpreter and allows developers to manipulate the runtime environment and access system-specific information.
  • Python allows you to write to files by way of the (w)rite and (a)ppend functions.

Let’s write our application. We’ll take it in small chunks, so it’s easier to comprehend.

Installing PyQt5

Before we can do anything, we must install PyQT5, otherwise the modules wouldn’t be available to our application.

To install PyQT5, log into your machine and issue the command:

pip install PyQt5

Once this completes, you’re ready to go.

Importing Our Libraries

The first thing we must do is import sys and then the modules that are required for our GUI.

Import sys with the line:

Next, we make the necessary sys modules available. Each of these comes from the PyQt5.QtWidgets library and includes the following:

  • QAppliation – handles widget-specific initialization and finalization.
  • QWidget – the base class of all user interface objects.
  • QLabel – provides a text or image display.
  • QLineEdit – a one-line text editor.
  • QPushButton – provides a command button.
  • QVBoxLayout – lines up widgets vertically.

The line looks like this:

So far, our app includes:

Define Our Widget

The next section defines our widget and looks like this:

The above code creates a new class, called UserInputApp that uses the QWidget binding and initializes the class. Next, it calls the parent class constructor and then initializes the UI elements with the init_ui method.

We then set the title and geometry of our widget with the following code:

Note: def __init__(self): is a special Python method known as the constructor (or initializer) method. It is used to initialize a newly created object instance of a class.

Allow the GUI for Entering Text and Saving to a File

We now set up our GUI for entering text and saving it to a file. This code is as follows:

A bit on the above code:

  • self.label = QLabel(‘Enter text:’): – creates a QLabel widget with the text ‘Enter text:’.
  • self.text_input = QLineEdit(): – creates a QLineEdit widget as an input field for the user to enter text.
  • self.save_button = QPushButton(‘Save to File’): – creates a QPushButton widget with the text ‘Save to File’.
  • layout = QVBoxLayout(): – creates a QVBoxLayout object (a vertical layout manager used to arrange widgets vertically in a UI).
  • layout.addWidget(self.label): – adds the label widget.
  • layout.addWidget(self.text_input): – adds the text_input widget.
  • layout.addWidget(self.save_button): – adds the save_button widget.
  • def save_to_file(self): – is responsible for saving the text entered by the user in the text_input widget to the file, user_input.txt.
  • text = self.text_input.text(): – retrieves the text entered by the user text variable.
  • with open(‘user_input.txt’, ‘a+’) as file: – opens the user_input.txt file in append mode (‘a+’).
  • file.write(text + ‘\n’): – writes the text entered by the user, followed by a newline character, to the user_input.txt.
  • print(‘Text saved to file.’): – prints a message to the console (terminal window) indicating that the text has been saved to the file.

Initialize and Run the Application

The final code section looks like this:

Here’s what each line does:

  • if __name__ == ‘__main__’: – checks if the script is being run directly as the main program instead of being imported as a module.
  • app = QApplication(sys.argv): – initializes a QApplication instance.
  • window = UserInputApp(): – creates an instance of the UserInputApp class that represents the main window of our application GUI.
  • window.show(): – displays the main window created in the previous step so it’s visible to the user.
  • sys.exit(app.exec_()): – starts the PyQt application event loop by calling app.exec_() to keep the GUI open until it is closed by the user.

The Full Code

The full code for our application looks like this:

Let’s call that application inputGui.py. Save the code to a file by that name and run it with:

python3 inputGui.py

A small GUI will pop up, asking for the user to enter some text (Figure 1).

Figure 1

Our Python GUI is running.

After the user enters text, they click Save to File and whatever they typed will be appended to the file user_input.txt. Keep adding new text and clicking Save to File and you’ll keep appending text to the file. When you’re finished, close the GUI and you’re done.

And that’s how you can create a Python GUI with PyQT5 that accepts user input and appends it to a text file.

YOUTUBE.COM/THENEWSTACK

Tech moves fast, don’t miss an episode. Subscribe to our YouTube
channel to stream all our podcasts, interviews, demos, and more.


Group Created with Sketch.



Source link

Exit mobile version