gui zero – making Python GUIs really simple

The code in this post has been updated to reflect the changes in guizero version 0.4.

When I was a teacher, I found it frustrating that it was not at all easy for students to create GUIs using Python. I used tkinter a little bit with my GCSE class and they instantly loved creating GUIs, but became frustrated because simple things were so difficult to do. After talking with some developers about this at Pycon UK, I decided to do something about it, and so I wrote a library called guizero which is meant to be used by children and removes all the unnecessary nasty bits without removing the intellectual requirements. Another thing which is important to me is that guizero is very easy to install and get started with – so there’s a completely no faff installation process, which is a winner if you’re struggling with getting your school techies to install things.

Download guizero and read the documentation here

But, promo flannel aside – is it any good for use in the classroom? On the CAS resources site, Stuart Lucas posted a popular “Book of programming challenges” resource (9651 downloads at the time of writing) so I thought I’d put guizero to the test to see how easy it is to complete a few of his challenges with a GUI and let you see for yourself.

Challenge 1

Write a program that will display a joke. Don’t display the punchline until the reader hits the enter key.
Extension: display the punchline in a different colour.

from guizero import App, Text, PushButton

# Method to call when button pressed
def display_joke():
   punchline.value = "Poke him on"
   
# Set up the app
app = App("Joke teller")

joke = Text(app, "How do you get Pikachu on a bus?")
punchline = Text(app, text="", color="red")
button = PushButton(app, display_joke, text="Display punchline")

app.display()

challenge1

So this was pretty straightforward. I created two pieces of text and a button, with the second piece of text remaining blank until the button is pressed, at which point it fills in the punchline.

Challenge 2

Write a program that will ask you your name. It will then display ‘Hello Name’ where ‘Name’ is the name you have entered.

from guizero import App, Text, TextBox, PushButton

# Method to display the greeting
def display_greeting():
   text.value = "Hello " + name.value

# Set up the app
app = App("Hello machine")

text = Text(app, text="What is your name?")
name = TextBox(app)
button = PushButton(app, display_greeting, text="Greet me")

app.display()

challenge2a challenge2b

This challenge makes use of the get() and set() methods of the Text and TextBox widgets to easily get values typed in and display them elsewhere on the page.

Challenge 3

Write a program to work out the area of a rectangle. Collect the width and height of the rectangle from the keyboard. Calculate the area and display the result.

Extension: Display the volume of a cuboid. See what happens when you don’t type in numbers! Try to explain what has happened and why.

from guizero import App, Text, TextBox, PushButton, error

# Method to calculate the area
def calculate():

    # Validation to check whether they typed in numbers
    if not height.value.isdigit() or not width.value.isdigit():
        error("Input error", "You must type in numbers for height and width")
    # Depth is allowed to be a digit or blank
    elif not depth.value.isdigit() and depth.value != "":
        error("Input error", "You must type in a number for depth")

    # Perform the calculation
    else:
        area = int( height.value ) * int( width.value )
        if depth.value == "":        
            result.value = str(area) + "cm squared"
        else:
            volume = area * int(depth.value)
            result.value = str(volume) + "cm cubed"
        

# Set up the app
app = App("Area and Volume calculator", layout="grid")

width_label = Text(app, text="Width:", grid=[0,0], align="left")
width = TextBox(app, grid=[1,0], align="left", width=30)

height_label = Text(app, text="Height:", grid=[0,1], align="left")
height = TextBox(app, grid=[1,1], align="left", width=30)

depth_label = Text(app, text="Depth:", grid=[0,2], align="left")
depth = TextBox(app, grid=[1,2], align="left", width=30)

button = PushButton(app, calculate, text="Calculate", grid=[1,3])

result_label = Text(app, text="Result:", grid=[0,4], align="left")
result = TextBox(app, grid=[1,4], align="left", width=30)

app.display()

challenge3a challenge3b challenge3c

This challenge was a little tricker. I used a grid layout so make the interface look tidy and line up the boxes properly. However, it wasn’t the GUI part which generated most of the code here, it was the validation. Since the get() methods always return strings I had to cast them to integers to do calculations (but this should already be familiar to students). I also saw a good excuse to use the error() box function to pop up a message if the validation check didn’t pass.

What do you think?

I’d love to hear your thoughts on guizero – whether they are positive or negative. Is this useful for you and your students? Is there something you’d like it to do but it doesn’t currently do? Would you like to see a tutorial on how to do a particular thing? Is there a bug? You can find the project on GitHub and add issues/ideas here, or leave a comment on this post, or tweet me @codeboom with your thoughts.

Advertisements

Cat Cat Code Ltd

So here it is! I’m taking the plunge as of September and starting my own business – Cat Cat Code Ltd.

I’ve put up a blog post with some tips on teaching HTML and CSS on the site so please do pop over and have a look. If you know of someone who could benefit from some Computer Science expertise then I’d be extremely grateful if you would send them my way. I’m also not currently booked for BETT so I’m available for work there.

PS Fear not, this blog is not going to descend into a relentless spam of advertising, I just thought I’d give you a heads up and now it’s back to business as usual!

 

Computing – the cake is a lie

I’m nearly at the end of my first time round teaching GCSE Computing and something has been bothering me. I decided to leave the topic of networking until the end, because I think it’s one of the hardest and also because I thought it would be beneficial to do it in Year 11 when my students are at their most knowledgeable. So I am teaching such objectives as:

“f) explain the terms IP addressing, MAC addressing, packet and protocols”

Eh? That’s quite a big ask really, isn’t it. My Year 11 group are as sharp as a hedgehog carrying a bag of knives to a cactus convention, so when I offer my GCSE level definitions with a casual “this is the stuff you need to know for the exam” I get questions along the lines of:

  • Why does a computer on a LAN need a MAC address and an IP address?
  • If packets are addressed to and from an IP address, how does that work when IP addresses are allocated dynamically?
  • Is it possible for someone with malicious intentions to create two pieces of hardware with the same MAC address? or to ‘steal’ your MAC address?
  • If a web server has an IP address which is looked up via DNS, how is it possible to host multiple websites on the same server with different domain names?

Now if you read the textbook, it just glosses over all of these things, which is sort of fair enough because a GCSE textbook isn’t meant to be a comprehensive tome on networking. I’m also not saying that I either don’t already know the answer or am lacking the ability to look up the answer to these things. The point I’m making is not that I need some help googling this stuff – stand down industry, I’ve turned off the bat signal. I’m stuck in a hideous choose your own adventure game where you can’t cheat and turn ahead. Do I…

a) Say “that’s not on the spec, don’t worry about that”
(crushing the student’s natural curiosity and undermining their confidence in me)

b) Say “I don’t know but I think it’s probably because of x…”
(fudge over the details until they get bored, not something I enjoy doing to my students, and something they HATE)

c) Tell the student the real answer
(and in the process waste lesson time on something that isn’t going to come up in the exam, confusing some students and opening up all sorts of other “but why is THAT” time sink questions)

No option is acceptable. It’s like when I did GCSE Biology and then I found out afterwards that everything I had learnt was actually a vastly simplified version of reality. And the cake being a lie doesn’t stop at GCSE – it’s all over A-Level as well. Computer architecture and processor design? A lie. Compilers? Lies. Networking? Still fib-a-licious. I really hope Professor Davenport doesn’t show up and say that everything in Uni networking lectures was a lie too otherwise I might cry.

So what do YOU do about this?

 

Image from http://cdn.meme.am/instances/250×250/59745067.jpg

How do you actually teach programming?

This is a question which has been bugging me for some time now – how do you actually teach someone to program? I don’t mean which language, or what resources should I use, or what time of the day is optimal. I mean what is it in your teaching which switches on the little lightbulb that makes a student able to think through the logic of what they want to do and translate that into code? I have recently been working on my Spanish using Duolingo and I sense that my own language learning is a little like what I’m seeing in the classroom with students who learn to code.

Here are the stages I often see in the classroom:

Syntax wizard
This is the first stage where the student is confident to use familiar concepts such as input, print, if/else etc. The student can memorize syntax and fix any errors that may occur. Confidence at this stage is usually quite high as it is early on in the learning journey, and you have probably provided a lot of help as well as offering fairly small and basic tasks. (Check out the super awesome diagram below produced by my art department.)

 

confidencecompetence

Pile of Lego
This bit is horrible for teachers. So, you’ve given your students a huge pile of programming building blocks to work with – they have understood conditions, loops, arrays, all the basics are there. So there you are with your special occasion turquoise pen, filling in your planner with glee, when you decide to set a more difficult task which combines some of these together. Here’s my favourite example of such a piece of thinking:

Teacher: Hmm, okay. I’ve taught input, loops and the % operator and everyone in the class did really well in those lessons. I know! Let’s put these familiar things together and ask them to write a program where they enter a number and the program prints out all of the even integers from 1 to the number they entered. 

Student: Burrr…what’s an integer?

Now, of course your students have not completely forgotten everything they once knew. They have just worked themselves into a panic (warning, this panic is contagious) because you asked them to put together more than one thing at once. It’s a bit like when on my Spanish Duolingo practice it asks me to write something involving two different tenses and some bit of vocab I only just learnt. Give me a test on each of these things individually and it’s ¡muy bien hecho!, but make me do them all together and it’s not exactly creme de la menthe, if you catch my drift Rodney.

Typewriter monkey
Upset by the loss of their former syntax wielding wizard glory where the challenges were easy and the gratification was quick (thanks a LOT, smartphone game culture x_x), students often get disheartened. Now, the way to program really difficult stuff goes something like this:

  1. Write some code. It doesn’t matter what it does, or even if you have any idea what it is supposed to do.
  2. Run your program
  3. If it doesn’t work, delete words and/or syntax from the code COMPLETELY AT RANDOM.
  4. Repeat 1-3 until either the code works, someone tells you the answer, or it’s the end of the lesson.

 

This is where the journey ends for some of the brave adventurers, they choose the wrong path*, Treguard packs them off home with a knapsack and they never enter the computer room again. However, for those who prevail, one day they turn up as…

Code Kitten
This student can code. They understand how to put together the building blocks and they aren’t phased by bigger programming tasks, e.g. programming hangman, noughts and crosses etc. They can think through how they will represent what they need to do using variables and data structures, and whilst they are only a kitten in experience terms, they are more than scrappy enough to hold their own in most tasks. I’d say this equates to a working fluency in a different language – good enough for most everyday situations, not good enough to read a newspaper.

But the question I ask is…how do you get your students from monkey to kitten? What is it in your lesson that takes them from random button bashing to confidence in building up their own code? For me, it’s all about the way I teach them to plan. Teaching syntax is satisfying and straightforward, indeed many ‘learn to code’ resources don’t go past the syntax wizard stage because they don’t want the student to lose interest. Teaching mastery is hard. But… that’s a post for another time 🙂

 

* By the wrong path I mean they probably opted to do something else instead of Computer Science GCSE. 😉

Computing – A beautiful dream

I didn’t believe the hype on the news about bad teachers. I mean, nobody I worked with was rubbish at their job so I put it down to teacher bashing media nonsense and got on with my life. I was happy to share my resources here and on CAS and to help people who asked for my help, because I understood I was part of a community where educated people treated each other with respect, were friendly and acted with professionalism. I understood that the government’s changes to my subject had taken some unawares and that there were people out there who needed support and help with transitioning to teaching a new subject and I would give whatever I could to help them. I was enthusiastic about anything and everything to do with teaching Computing, making new friends and building a network of people I hoped would be mutual supporters.

And then I woke up from a beautiful dream.

It’s now one year on from the introduction of the new Computer Science curriculum and my eyes have been well and truly opened to some of the nasty truths that are out there, lurking in my profession.

Asking for personal help

Having been a CAS Master Teacher, I have got used to people asking for things. People asking me to come to their school, to give them a scheme of work, to advise them on XYZ. Now don’t get me wrong, I’m a strong advocate of openness, sharing and collaboration but generally when you collaborate and share both parties are meant to benefit. This sounds more like one of those dogsbody jobs that you try to get inexperienced people to do by telling them “it’ll be good for your CV” (ha ha, sucker!). Yet, this is apparently now a totally fine thing to do. Master Teachers are meant to help people in their area, they are not your personal scheme of work slave. Last week I had two emails from random people who don’t live anywhere near me, who I’ve never met, asking for pretty specific advice about teaching Computing. Working with someone with the outcome of mutual benefit for both parties is fine, even if the benefit for one party is just the satisfaction of helping someone. Expecting people to do your job for you is not fine, it’s embarrassing.

Not improving subject knowledge

CAS runs events to help Computer Science teachers get to know each other and to connect with industry pros, many of whom are very willing to help (and it’s important to let industry know how to help!) I went to a hugely helpful session a few weeks back where a local teacher shared his experience of GCSE Controlled Assessment. How many teachers turned up? 3. How many teachers say they need help yet never seem to be able to turn up to a training course or meeting? I’ll leave that as an exercise to the reader. It’s totally unprofessional and unacceptable to not have the subject knowledge you need and yet to do nothing proactive about it. If you really care you’ll make the time – as demonstrated by many amazing teachers who have gone from zero to awesome and are now helping others.

Breaking copyright

Now on to the PG Online resource copying scandal. Apparently, 1200 people were members of a Facebook group where people were illegally sharing paid PG Online resources with others. I know how long it takes to write resources having spent my entire summer holiday last year writing A-Level resources for Cambridge Press so I can imagine how much of a blow this must be to the people running PG Online. Have we really got to the stage where some teachers think it is OK to break the law? Anyone else find it totally ironic that copyright law is even covered in the things we teach?! Not cool, Computing community.

Failure to respect Creative Commons

So do free resources fare any better than the paid for ones? No! I thought part of being a teacher was the craft of putting together a series of lessons, planning out what you were going to do and how your students would progress. Arguably this is even more important if you’re not as confident in the subject matter. Yet all I see is a feeding frenzy of people after a quick fix, endless “can anyone send me a scheme of work for X” posts and a flagrant disregard for Creative Commons. Here’s an example – a resource was removed from CAS by its author, presumably after many complaints from people whose work was reproduced inside it without acknowledgement (this was later fixed). In the comments section, do we see upstanding members of the community reminding each other that plagiarism is bad (more irony here as we teach this too) or do we see comments like

“Why has it been removed? I had already downloaded it some time ago. Anyway it remains available in the resource history”

 

What! So instead of acknowledging that people who poured hard work into something deserve to be credited as authors and it is wrong not to do so, some of the people in my profession are actually more interested in screwing over the people who make the resources they use by telling others the ‘back door’ way to get at the unaccredited material. Thanks guys, really feel you’ve got my back. How is the outside world expected to take teaching seriously as a profession if we don’t respect each other’s right to be acknowledged for our work?

Yeah OK it’s a rant 😉

I know that people always say I rant in posts (which is mostly because I only remember to do a blog when I’m seriously cheesed off). However I think we as a community need to make a stand and say ‘not cool’ when this kind of thing happens. Behaviour like this is burning out the good will of so many good people who want to help, and it makes me embarrassed to have the same job title as someone who makes a total mess of teaching the subject I love. Please stop doing this. I don’t want the media to be right.

Javascript Binary to Denary

I wrote this but I am not sure I can use it for the purpose I wanted. Feel free to use if it’s useful to you!

<html>
<head>
<style>
input[type='text'] {
   font-size: 24px;
}
</style>
<script type="text/javascript">

// A quick and dirty binary to denary converter in Javascript
// I wrote it to use with Year 9 students but not sure it meets my  
// objectives, so here it is for you!
// By @codeboom codeboom.wordpress.com

function generate_denary(form) {
// Generate the denary number by multiplying the digits by their place value and adding together
   var denary = 8 * parseInt(form.first.value) + 
   4 * parseInt(form.second.value) +
   2 * parseInt(form.third.value) + 
   parseInt(form.fourth.value);
   form.denary.value = denary;
}

function generate_binary(form){

   // Reset the form if they tried to enter a number we can't make with 4 bits
   if(form.denary.value > 15) {
      alert("That number is too big to make with 4 bits!");
      form.denary.value = 1;
      form.first.value = 0;
      form.second.value = 0;
      form.third.value = 0;
      form.fourth.value = 1;
   }
   else {
      var binary = "";
      var current = form.denary.value;

      // Repeatedly divide by 2, see if there is a remainder
      // and store it as the binary digit
      for(var i=0; i<4; i++){
         var digit = current % 2;
         binary = digit + binary;
         current = Math.floor((current - digit)/2);
      }

      // Set the values you worked out into the boxes
      form.first.value = binary.charAt(0);
      form.second.value = binary.charAt(1);
      form.third.value = binary.charAt(2);
      form.fourth.value = binary.charAt(3);
   }

}
</script>

</head>
<body>
<form>
<h1>Binary number</h1>
<input type="text" name="first" style="width: 50px;" maxlength="1" onchange="generate_denary(this.form)">
<input type="text" name="second" style="width: 50px;" maxlength="1" onchange="generate_denary(this.form)">
<input type="text" name="third" style="width: 50px;" maxlength="1" onchange="generate_denary(this.form)">
<input type="text" name="fourth" style="width: 50px;" maxlength="1" onchange="generate_denary(this.form)">

<h1>Denary number</h1>
<input type="text" name="denary" onchange="generate_binary(this.form)">
</form>

</body>
</html>

Being a 21st Century Teacher

So I’m applying for the Picademy – two days of visiting Raspberry Pi towers, meeting cool people and fiddling around with a tiny computer – sounds good to me! One of the requirements for the application is to write a blog post about “Being a 21st Century Teacher”…which is actually quite a tricky topic to write about, especially when you haven’t blogged in ages!

As I mentioned in a previous post, possibly the most irritating thing you can say in passing to a teacher of Computing and ICT is how hard it must be to “keep up with the kids these days”. It’s simply not true, even for the least experienced teacher of Computing, that what we are doing is simply keeping up with the kids. Learning about the principles of Computer Science is very different to fannying about on 2048 and tweeting a selfie. Possibly both equally mystifying to most over 50’s, but definitely not even remotely similar. As a 21st Century teacher, getting past this perception is one of our challenges.

As a 21st Century teacher I also feel that our professionalism is assaulted on all sides – the media complains of ‘lazy teachers’ and claims abound that we need industry to “step into the breach” to teach children the skills they need to progress in the tech industry. There is a huge need at the moment for CPD for teachers and a huge amount of teachers are acting incredibly professionally, spending their own time and money on improving their skills so that they can use their wealth of pedagogical expertise to teach the next generation Computing skills. Of course schools need to work together with industry, but industry also needs to realise that school is a grounding in all subject areas not a bootcamp for churning out their ideal employees. School will never be a replacement for training, and even the most experienced teachers can’t teach ALL THE THINGS. So, one of the things I must do as a professional educator is to ensure I am sufficiently up to date that I am teaching my students concepts which will be useful to them. It’s no good teaching these concepts with tools that went out of date 8 or 9 years ago when I first started teaching, just because I can’t be bothered to update my scheme of work. (On that note, would somebody put a stake in Access already?!)

And this is why I’d like to go to the Picademy! Yes, I have a degree in Computer Science, I can program, I’m already teaching Computing and I run training for other teachers. It would be easy to become complacent and spend my entire holidays playing Hearthstone. (Oops.) However, every time I go to an event, run training course, go on a course or check my Twitter, I learn something new. I see something someone else is doing and I’m not. I’ve lost count of the times people have come to me for training and I’ve ended up learning about something cool from them too. I’m also a big fan of sharing things – at the end of the day, if it means more children get a better education then that makes me happy 🙂