I just starting out with PyQt5, and I am stuck trying to get a button to call a function. I have been learning Python for a couple months and wanted to build a basic GUI app. I followed some tutorials online, but for some reason, clicking the button doesn’t seem to run the function I made.
Here is a stripped-down version of my code, in case it helps:
It looks like you are attempting to follow a model-view-controller (MVC) architecture. Without seeing the tutorial you are following and the entirety of your code I can’t say for certain why _calculate isn’t working properly for you.
Admittedly, I am not very familiar with MVC programs so I won’t attempt to give you any advice there, maybe someone else will chime in for you on that. What I can do is point you down a simpler road for creating your first PyQt applications. What I’ve included for you below is a simple application with a single button. The app defines a class MainWindow which inherits the widget QMainWindow and explicitly defines the widgets to use in that window. You can use this boiler plate code as a foundation to flesh out your own creation.
Let me know if you have any questions about this code. Good luck!
-Trever
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
from PyQt5.QtCore import pyqtSlot # Decorator to identify a function as a slot
class MainWindow(QMainWindow):
"""Extend the QMainWindow as the base for you app."""
def __init__(self):
"""Initialize MainWindow."""
# Run __init__ for QMainWindow
super().__init__()
# Give the window a title
self.setWindowTitle("Push Button Example")
# Resize the window so whole title is visible.
self.resize(300, 50)
# Define the button
self.push_button = QPushButton("Push Button")
# Assign the 'clicked' signal to a slot
self.push_button.clicked.connect(self.button_clicked)
# Make the button the central widget
# Normally, the button would be added to a "central layout" which is
# assigned to a central widget, but for brevity, I'm ommiting the
# layout.
self.setCentralWidget(self.push_button)
# The decorator isn't stricly required, I just like using it. It comes in
# really handy when you need to retrieve a value from the sending widget.
@pyqtSlot()
def button_clicked(self):
"""Slot to hold the instructions for when the button is clicked."""
print("You clicked the button!")
# Define script if file is run directly. Ignored if MainWindow is called from
# another file.
if __name__ == "__main__":
import sys
# Instantiate application
app = QApplication(sys.argv)
# Instantiate and show MainWindow
main_window = MainWindow()
main_window.show()
# Execute the application
sys.exit(app.exec_())