Over the last few days we have been learning how to organize GUI elements in a window, most recently using a box layout. Today we are continuing our work in this area.
Our task is to create a program named yourname-qt-dieroller.py that displays a face of a die in a window along with a button. Each time the button is clicked, the die is “rolled” and new face is displayed.
To make this happen, you’ll need a few things. First, I have placed the images of six die faces in a folder on the N: drive. Copy all six images to your H: drive.
I suggest that you store the names of these images in a list so that you can access them by a random number (0-5). The list might look like this:
self.dice = ["die_face_1.png", "die_face_2.png", "die_face_3.png", "die_face_4.png", "die_face_5.png", "die_face_6.png"]
To create a random number we’ll need help from the random module and its randint() function:
from random import randint
I suggest designing your layout with a “vbox” that holds two “hbox” containers. The first “hbox” will contain the label with the image of the die face, the second hbox will hold the button. This drawing outlines what we’ll shoot for:
You should probably begin your work by just getting one die (say, five) to show up along with the button. Once you have the pieces in place, you can add the action.
Making It Roll
Our button will be connected to an event handler, usually named buttonClicked(). This method will create a new random integer from zero to five and then put a new image in the label. In order for the buttonClicked() method to access the label in the first hbox, the label must be a property of the window. So when you first create the label, make it part of self:
pixmap1 = QtGui.QPixmap("die_face_5.png") self.lbl1 = QtGui.QLabel(self) self.lbl1.setPixmap(pixmap1)
Then, in the buttonClicked() method, you can access the label and change its picture with the line:
Of course I’m leaving it up to you to create the random number and retrieve the new file name from the list of dice and get the image stored in pixmap.
Wrapping It Up
As you get your program working, you may notice that the images’ white background does not display nicely with the beige color of the window. We can make the background of the window white by placing the the following code in the setup for the GUI:
# Set Background Color p = self.palette() p.setColor(self.backgroundRole(), QtCore.Qt.white) self.setPalette(p)
If everything goes according to plan, your window will look similar to the image below:
Turning It In
Once the program is working, please submit it with the filename yourname-qt-dieroller.py using this submission link.
Extending the Code
As a challenge, make another program that rolls five dice at once. Call it the Yahtzee Dice Roller 🙂