Python-QT:点击按钮后主窗口意外关闭,退出码1无错误提示
Hey there! No worries about any English grammar slips—we’re all here to troubleshoot and learn together. Let’s figure out why your BMI calculator window closes when you click the calculate button, with exit code 1 but no error messages.
First, let’s break down the most common causes and fixes for this issue:
1. Add Exception Catching to Spot Hidden Errors
Exit code 1 usually means an unhandled exception is crashing your program, but Qt might not show it by default. Let’s wrap your calculation logic in a try-except block to catch and print the error:
def calculate_bmi(self): try: # Grab input values (adjust variable names to match your code!) weight = float(self.weight_input.text()) height = float(self.height_input.text()) # Calculate BMI bmi = weight / (height ** 2) # Update result label self.result.setText(f"Your BMI: {bmi:.2f}") except Exception as e: # Print the error to your console print(f"Oops, something went wrong: {str(e)}") # Optional: Show a pop-up error message from qtpy.QtWidgets import QMessageBox QMessageBox.critical(self, "Error", f"Problem calculating BMI: {str(e)}")
Run your program again and check the console—this should tell you exactly what’s breaking (like invalid input, a missing UI element, etc.).
2. Double-Check Your Button Connection
A common mistake is calling the function instead of binding it to the button’s click event. Make sure your connection line looks like this:
# Correct: Pass the function reference (no parentheses!) self.calculate_button.clicked.connect(self.calculate_bmi)
If you wrote self.calculate_button.clicked.connect(self.calculate_bmi()), the function runs immediately when the program starts, and the button tries to use its return value (which isn’t a callable), leading to a crash when clicked.
3. Verify Your "result" Label is Properly Initialized
If your result label wasn’t created correctly in your window’s __init__ method, trying to update it will throw an error. Double-check that you have something like this:
def __init__(self): super().__init__() # ... other UI setup ... self.result = QLabel("BMI result will appear here") # Add the label to your layout so it’s part of the window self.layout.addWidget(self.result)
If self.result doesn’t exist, accessing it in your calculate function will cause an AttributeError that crashes the program.
4. Confirm Your Event Loop is Set Up Correctly
Make sure your main execution block ends with Qt’s event loop—this keeps the window open until you close it:
if __name__ == "__main__": app = QApplication(sys.argv) window = YourBMICalculatorWindow() window.show() # Use app.exec() for Qt6, app.exec_() for older versions sys.exit(app.exec())
Without this, the window might close unexpectedly, though this usually happens right away rather than on button click.
Try these steps one by one—chances are the exception catch will point you directly to the problem. Let me know what the error message says if you need more help!
内容的提问来源于stack exchange,提问作者J-Gallus

