Docsity

Python este es un documento de python para aprender matematicas, Resúmenes de Matemáticas

Toggle sidebar
bg1
Would you like to add buttons, boxes, pictures and colours
and more to your Python programs? This book will show you
how to create Python desktop applications using the guizero
library, which is quick, accessible, and understandable for all.
This book is suitable for everyone, from beginners to
experienced Python programmers who want to explore
graphical user interfaces (GUIs).
There are ten fun projects for you to create, including a
painting program, an emoji match game, and a
stop-motion animation creator.
Create games and fun Python programs
Learn how to create your own graphical user interfaces
Use windows, text boxes, buttons, images, and more
Learn about event-based programming
Explore good (and bad) user interface design
Create your own
graphical user interfaces
on any computer
Laura Sach Create graphical user interfaces with Python Martin O’Hanlon
Create Graphical User
Interfaces with Python
Laura Sach Martin O’Hanlon
How to build windows, buttons, and widgets
for your Python projects
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Vista previa parcial del texto

¡Descarga Python este es un documento de python para aprender matematicas y más Resúmenes en PDF de Matemáticas solo en Docsity!

Create Graphical User

Interfaces with Python

Laura Sach Martin O’Hanlon

How to build windows, buttons, and widgets

for your Python projects

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

CREATE GRAPHICAL USER INTERFACES WITH PYTHON

Welcome!

T

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

CREATE GRAPHICAL USER INTERFACES WITH PYTHON

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

A

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

Introduction to GUIs

How to install guizero and create your first app

Chapter 1

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:

from guizero import App

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:

app = App(title="Hello world")
app.display()

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:

from guizero import App, Text
app = App(title="Hello world")
message = Text(app, text="Welcome to the app")
app.display()

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:

message = Text(app, text="Welcome to the app")

Figure 1 Your first guizero app

Chapter 1 Introduction to GUIs 11

CREATE GRAPHICAL USER INTERFACES WITH PYTHON

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

from guizero import App, Text
app = App(title="Hello world")
message = Text(app, text="Welcome to the app")
app.display()

01-helloworld.py / Python 3 DOWNLOAD magpi.cc/guizerocode

Chapter 2 Wanted Poster 13

CREATE GRAPHICAL USER INTERFACES WITH PYTHON

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:

from guizero import App
app = App("Wanted!")
app.bg = "yellow"
app.display()

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:

app.bg = "#FBFBD0"
app.bg = (251, 251, 208)

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.

from guizero import 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:

from guizero import App, Text

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:

from guizero import App, Text
app = App("Wanted!")
app.bg = "#FBFBD0"
wanted_text = Text(app, "WANTED")
app.display()

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.

from guizero import App, Text, Picture

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.

cat = Picture(app, image="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

CREATE GRAPHICAL USER INTERFACES WITH PYTHON
from guizero import App, Text, Picture
app = App("Wanted!")
app.bg = "#FBFBD0"
wanted_text = Text(app, "WANTED")
wanted_text.text_size = 50
wanted_text.font = "Times New Roman"
cat = Picture(app, image="tabitha.png")
app.display()

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

CREATE GRAPHICAL USER INTERFACES WITH PYTHON
# App -------------------
app = App("TOP SECRET")
# Widgets ---------------
title = Text(app, "Push the red button to find out your spy
name")
# Display ---------------
app.display()

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.

button = PushButton(app, choose_name, text="Tell me!")

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:

NameError: name 'choose_name' is not defined

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:

def choose_name():
print("Button was pressed")

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