




























































































Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity
Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium
Esta página no es visible en la vista previa
¡No te pierdas las partes importantes!





























































































2 CREATE GRAPHICAL USER INTERFACES WITH PYTHON
4 CREATE GRAPHICAL USER INTERFACES WITH PYTHON
Martin O'Hanlon Martin works in the learning team at the Raspberry Pi Foundation, where he creates online courses, projects, and learning resources. He contributes to the development of many open-source projects and Python libraries, including guizero. As a child, he wanted to be a computer scientist, astronaut, or snowboard instructor.
Laura Sach Laura leads the A Level team at the Raspberry Pi Foundation, creating resources for students to learn about Computer Science. She somehow also manages to make cakes, hug cats, and wrangle a toddler.
About the authors...
5
his book will show you how to use Python to create some fun graphical user interfaces (GUIs) using the guizero library. The guizero library started with the belief that there must be an easier way for students in school to create Python GUIs. The library itself was born one day on a long train journey from Cambridge, as the side project of a secondary school teacher. Guizero has grown significantly in terms of features, yet remained true to its original aim of being simple but flexible. It is a library for all beginners to create with, for teachers to scaffold learning with and for experts to save time with. We hope that these projects and guizero brings you that little spark of excitement to your Python programs. That spark might be anything from a button that does something when you click it, to colours in your otherwise black and white Python programming, to a full multicoloured Waffle. It turns out that with open-source software, even if you don't know how to get the whole way there, if you start, someone will help you. We are grateful to the many contributors who have put time and effort into creating guizero, and to the thousands of people who have used it in their projects. Enjoy your journey and be proud of your creations.
Laura and Martin
7
Chapter 8: Flood It 078 Create a more complex Waffle-based puzzle game
Chapter 9: Emoji Match 092 Make a fun picture-matching game
Chapter 10: Paint 110 Create a simple drawing application
Chapter 11: Stop-frame Animation 124 Build your own stop-frame animated GIF creator
Appendix A: Setting up 138 Learn how install Python and an IDE
Appendix B: Get started with Python 142 How to start coding in Python
Appendix C: Widgets in guizero 148 An overview of the widgets used in guizero
8 CREATE GRAPHICAL USER INTERFACES WITH PYTHON
graphical user interface (GUI, pronounced ‘gooey’) is a way of making your Python programs easier to use and more exciting. You can add different components called ‘widgets’ to your interface, allowing lots of different ways for information to be entered in to the program and displayed as output. You might want to allow people to push a button, to display a piece of text, or even let them choose an option from a menu. In this book we will use the guizero library, which has been developed with the aim of helping beginners to easily create GUIs. Python’s standard GUI package is called tkinter, and is already installed with Python
How to install guizero and create your first app
WHAT YOU'LL NEED You will need a computer (e.g. Raspberry Pi, Apple Mac, Windows or Linux PC) and an internet connection for the software installation. You will also need the following software installed:
- Python 3 (python.org) – see Appendix A - An IDE (code editor), e.g.: IDLE (installed with Python 3), Thonny (thonny.org), Mu (codewith.mu), PyCharm (jetbrains.com/pycharm) - The guizero Python library (lawsie.github.io/guizero)
10 CREATE GRAPHICAL USER INTERFACES WITH PYTHON
Open up the editor where you will write your Python code. At the start of every guizero program, you will choose the widgets you need from the guizero library and import them. You only need to import each widget once, and then you can use it in your program as many times as you like. At the top of the page, add this code to import the App widget:
All guizero projects begin with a main window which is a container widget called an App. At the end of every guizero program, you must tell the program to display the app you have just created. Add these two lines of code underneath the line where you imported the App widget:
Now save and run your code. You should see a GUI window with the title ‘Hello world’ ( Figure 1 ). Congratulations, you’ve just created your first guizero app!
Adding widgets Widgets are the things which appear on the GUI, such as text boxes, buttons, sliders, and even plain old pieces of text. All widgets go between the line of code to create the App and the app.display() line. Here is the app you just made, but in this example we have added a Text widget:
Did you notice that there are two changes ( Figure 2 )? There is now an extra line of code to add the Text widget, and we have also added Text to the list of widgets to import on the very first line. Let’s look at the Text widget code in a bit more detail:
Figure 1 Your first guizero app
Chapter 1 Introduction to GUIs 11
Just like any variable in Python, a widget needs a name. This one is called ‘message’. Then we specify that we would like this to be a ‘Text’ widget. Inside the brackets are some parameters to tell the Text widget what it should look like. The first one, ‘app’, tells the Text where it will live. All widgets need to live inside a container widget. Most of the time your widgets will live directly inside an App, but you will discover later that there are also some other types of container widget you can put things in too. Finally, we tell the widget to contain the text “Welcome to the app”. Figure 2 Add a text message
01-helloworld.py / Python 3 DOWNLOAD magpi.cc/guizerocode
Chapter 2 Wanted Poster 13
Background colours Let's make the background of the app a bit different. Traditionally, wanted posters look like they are made of parchment, so let’s add a pale yellow colour instead as the background. Find the line of code where you create the app. Immediately after this line of code, add one more line of code to modify the bg property of the window. In this case, bg is short for ‘background’ and will let us change the colour of the background. Now your code should look like this:
This is called editing a property. In the code, you need to specify the widget you are talking about (app), the property you want to change (bg) and the value you want to change it to. You might think this colour ( Figure 2 ) is a bit too yellow, so let's look up the hex code of a different yellow colour. There are lots of websites where you can search for colours, for example you could try htmlcolorcodes.com ( Figure 3 ).
Figure 2 Background colour
Figure 3 Selecting a shade on htmlcolorcodes.com
14 CREATE GRAPH ICAL USER INTERFACES WITH PYTHON
When you have selected the colour you want, you will see its code displayed on the site either as hexadecimal (in this case #FBFBD0) or as RGB (251, 251, 208). You can use both of these formats for setting colours in guizero; for example, you could delete the code for making your background yellow and then try one of these options in your program:
Add some text Your app should look something like Figure 4. Now let’s add some text to the GUI. We will begin by adding the text that all good wanted posters need – the word ‘Wanted’! First, look for the line of code you already have where you imported the App.
You need to import Text to be able to create a piece of text, so add it to the end of the list. Now the line looks like this:
Every time you want to use a new type of widget, add its name to the end of the list. There is no need to keep adding whole new lines of code: just stick with one list so that your program doesn’t get too confusing. Now that you can use text, let's add a piece of text. Remember that all widgets on the GUI must be added between the line of code where you create the App and the line of code where you display it. Your code should now look like this:
Figure 4 Pale background
16 CREATE GRAPH ICAL USER INTERFACES WITH PYTHON
No ‘wanted’ poster would be complete without a picture, so let’s add one. My poster is going to be for my cat, because she is always scratching things she shouldn’t be. Save a copy of the image you would like to use in the same folder as your GUI program. You can use images in other folders, but if you do you will have to provide the path to the image, so it’s a lot easier to just store them in the same folder when you are starting out.
Hopefully you’re now getting used to adding widgets. Remember that they must always be imported at the top of the program, and then the widget created with a sensible name after the line of code where you create the App, but before the final app.display() line. Add 'Picture' to the list of widgets to import at the start of the program.
Now create a Picture widget with two parameters: the app and the file name of the picture. This is the code we used because our picture was called tabitha.png.
Run your code (which should look like 02-wanted.py ) again and you should see the picture displaying below your text ( Figure 7 ). Now it's up to you to use your new GUI customisation skills to style your poster however you would like.
IMAGE MANIPULATION Because guizero is a library for beginners and we wanted to make it as easy as possible to install, it does not come with the fancier image manipulation functions as these require an extra library called 'pillow'. You can always use non-animated GIF images on any platform, and PNG images on all platforms except Mac, so if you're not sure whether you have installed the extra image manipulation functions, stick to those image types.
Figure 7 The finished poster
Chapter 2 Wanted Poster 17
02-wanted.py / Python 3 DOWNLOAD
magpi.cc/guizerocode
READING THE DOCS
You might be wondering how to find out what properties a particular widget has that you can change. Even if you are a complete beginner programmer, it is worth learning how to read documentation because it will let you use the full power of guizero and any other libraries you come across.
The guizero documentation can be found at lawsie.github.io/guizero. Once you are there, click on the widget you would like to change, and scroll down until you reach the properties section. For example, if you select ‘Text’ under the heading of widgets, you will see all of the properties of a piece of Text that you can possibly change. Documentation also often contains helpful snippets of code which show you how to use a particular property or method, so don't be scared of having a look through – you never know what you might learn!
Chapter 3 Spy Name Chooser 19
Run this code and you should see a window with the text ( Figure 1 ).
Add a button Let's go ahead and add a button to the GUI. Add PushButton to your list of imports so that you can use buttons. (Be careful to use a capital B!) Underneath the Text widget, but before the app displays, add a line of code to create a button.
Your code should now look like spy1.py (page 22). Run it and no button will appear, but you’ll see an error in the shell window:
This is because choose_name is the name of a command which runs when the button is pressed. Most GUI components can have a command attached to them. For a button, attaching a command means “when the button is pressed, run this command.” A GUI program works differently to other Python programs you might have written because the order in which the commands are run in the program depends entirely on the order in which the user presses the buttons, moves the sliders, ticks the boxes or interacts with whichever other widgets you are using. The actual command is almost always the name of a function to run.
Figure 2 You now have a button
20 CREATE GRAPH ICAL USER INTER FACES WITH PYTHON
Create a function Let's write the function choose_name so your button has something it can do when it is pressed. Look at your program and find the functions section. This is where you should write all of the functions which will be attached to GUI widgets, to keep them separate from the code for displaying the widget. Add this code in the functions section:
Your code should now look like spy2.py. The button will now appear ( Figure 2 ). If you press the button, it may appear that nothing has happened, but if you look in your shell or output window, you will see that some text has appeared there ( Figure 3 ). Instructing your function to first print out some dummy text is a useful way of confirming that the button is activating its command function correctly when it is pressed. You can then replace the print statement with the actual code for the task you would like your button to perform. Inside your choose_name function, type a # symbol in front of the line of code that prints "Button was pressed". Programmers call this ‘commenting out’, and what you have done here is told the computer to treat this line of code as if it were a comment, or in other words you have instructed the computer to ignore it. The benefit of commenting a line of code out instead of just deleting it is so that if you ever want to use that code again, you can easily make it part of your program again by removing the # symbol.
BIG RED BUTTON At the moment, your button is not big or red! You used properties in the previous chapter to change the appearance of your text on the ‘Wanted’ poster, so can you use the properties of the PushButton widget to change the background colour and the text size? Note that it may not bepossible to change the colour of a button on macOS, as some versions of the operating system will not allow you to do so, but you should still be able to alter the text size.
Figure 3 Text is output to the shell window