Raspberry_Pi_Education_Manual

Notes:

Lesson 3.4: Getting artistic

Now we’ve learned to use functions, as well as manipulating data, let’s get back to something a bit more visual. This time we’re going to get on with displaying graphics, controlling widgets and using classes.

# Include the system and graphical user interface modules import sys

from PySide.QtGui import * class MyWindow(QWidget): def __init__(self):

super(MyWindow,self).__init__() # name the widget self.setWindowTitle('Window Events') # create a label (a bit of text) self.label = QLabel('Read Me', self) # create a button widget, position it and # connect a function when it is clicked button = QPushButton('Push Me', self) button.clicked.connect(self.buttonClicked) # create a vertically orientated layout box # for the other widgets

layout = QVBoxLayout(self) layout.addWidget(button) layout.addWidget(self.label) # track the mouse self.setMouseTracking(True)

def buttonClicked(self): """ Update the text when the button is clicked """ self.label.setText("Clicked") def mouseMoveEvent(self, event): """ Update the text when the (tracked) mouse moves over MyWindow """ self.label.setText(str(event.x()) + "," + str(event.y())) # start an application and create a widget for the window, # giving it a name

application = QApplication(sys.argv) # construct a widget called MyWindow widget = MyWindow() # show the widget widget.show() # start the application so it can do things # with the widgets we've created application.exec_()

Experiments in Python

94

Made with FlippingBook flipbook maker