Python PyQt Convert Kilograms To Pounds

By | September 20, 2023

Python PyQt Convert Kilograms To Pounds – To create a PyQt GUI program that converts kgs to lbs, you can use a similar approach as in the previous examples.

<yoastmark class=

Here’s a basic PyQt program to perform this conversion:

Source Code

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QLineEdit, QPushButton

class KilogramsToPoundsConverter(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('Kilograms to Pounds Converter')
        self.setGeometry(100, 100, 300, 150)

        # Create a vertical layout
        layout = QVBoxLayout()

        # Create input field for kilograms
        self.kilograms_label = QLabel('Enter kilograms:')
        self.kilograms_input = QLineEdit()

        # Create a label to display the result
        self.result_label = QLabel('Pounds:')

        # Create a button to perform the conversion
        self.convert_button = QPushButton('Convert')

        # Connect the button click event to the conversion function
        self.convert_button.clicked.connect(self.performConversion)

        # Add widgets to the layout
        layout.addWidget(self.kilograms_label)
        layout.addWidget(self.kilograms_input)
        layout.addWidget(self.convert_button)
        layout.addWidget(self.result_label)

        # Set the layout for the main window
        self.setLayout(layout)

    def performConversion(self):
        try:
            # Get the kilograms value from the input field
            kilograms = float(self.kilograms_input.text())

            # Perform the conversion: 1 kilogram = 2.20462 pounds
            pounds = kilograms * 2.20462

            # Display the result
            self.result_label.setText(f'Pounds: {pounds:.2f}')
        except ValueError:
            # Handle invalid input (e.g., non-numeric input)
            self.result_label.setText('Invalid input')

def main():
    app = QApplication(sys.argv)
    window = KilogramsToPoundsConverter()
    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

This code creates a PyQt application with a window containing an input field for the user to enter kilograms, a button to perform the conversion, and a label to display the result in pounds. When the user enters a value in kilograms and clicks the “Convert” button, the conversion is performed and displayed in the label.

Make sure you have PyQt5 installed (pip install PyQt5) before running this code.

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *