In this tutorial, we're going to talk about adding buttons and a bit about functionality of them, as well as adding a new, home, method to our Window class.
First, buttons have other "functions" besides simple graphical ones, since they tend to execute functions. This means we're going to need to also bring in QtCore, adding that to our imports:
import sys from PyQt4 import QtGui, QtCore
Next, our "home" method is a method that we want to immediately bring in on start up. While we could treat the __init__ method like a home method, this would mean calling the __init__ method to return to a home screen, and this would reset all other application changes. That would be a pretty bad system! To change this, in our __init__ method, we just need to replace the self.show() with self.home()
class Window(QtGui.QMainWindow): def __init__(self): super(Window, self).__init__() self.setGeometry(50, 50, 500, 300) self.setWindowTitle("PyQT tuts!") self.setWindowIcon(QtGui.QIcon('pythonlogo.png')) self.home()
self.home() does not yet exist, so let's create that next:
def home(self): btn = QtGui.QPushButton("Quit", self) btn.clicked.connect(QtCore.QCoreApplication.instance().quit) btn.resize(100,100) btn.move(100,100) self.show()
Once that is done, we're also going to create a final function for our application, calling it "run"
def run(): app = QtGui.QApplication(sys.argv) GUI = Window() sys.exit(app.exec_()) run()
Full code:
import sys from PyQt4 import QtGui, QtCore class Window(QtGui.QMainWindow): def __init__(self): super(Window, self).__init__() self.setGeometry(50, 50, 500, 300) self.setWindowTitle("PyQT tuts!") self.setWindowIcon(QtGui.QIcon('pythonlogo.png')) self.home() def home(self): btn = QtGui.QPushButton("Quit", self) btn.clicked.connect(QtCore.QCoreApplication.instance().quit) btn.resize(100,100) btn.move(100,100) self.show() def run(): app = QtGui.QApplication(sys.argv) GUI = Window() sys.exit(app.exec_()) run()
Here, we've created a button and made it execute built-in PyQT code. What if we want it to execute our own code instead? That's what we'll be covering next.