Python microbit basics: How to display images

Extend it with code
How can you improve it?

If you haven’t already had a look at the Image class documentation, now’s a great time, so that you can explore and try out the more advanced features that let you work with images and animations.

When you display an image on the screen it clears what was on the screen beforehand. If you want to show two images at the same time, you can add the images together using the + operator. The code sample below has two images: one of a person and one of a box:

from microbit import *
person = Image("00900:33333:00300:03030:03030")
               
box = Image("99999:90009:90009:90009:99999")

while True:
    # fade in
    for i in range(10):
        faded_box = box * 0.1 * i
        display.show(person + faded_box)
        sleep(100)

This code has two loops: one nested inside the other.

The while Trueloop on line 6 makes lines 7-11 repeat continuously.

The for i in range(10)  on line 8 makes lines 9-11 repeat 10 times

 

Notice how you can change the brightness of an image by multiplying it by a number using *(line 9) and how you can combine two images together by adding them using +(line 10)

Can you:

  1. Make a smiley face fade in and out?

    Hint: You can do this by either making lots of images of a smiley face then displaying them one after another, or by using Image.HAPPY  and changing the brightness with the *  operator

  2. Make a smiley face scroll left and right?

    Hint: Use the Image.shift_left()  and Image.shift_right()  functions: see the documentation for further details.

  3. Make a smiley face fade in when you press button A and fade out when you press button B?

    Hint: You can use something like this to check if the buttons have been pressed, but you’ll need to put it inside a loop and tell it how to fade in / fade out:

    if button_a.is_pressed():
       # fade in
    if button_b.is_pressed():
       # fade out
    

Leave a Reply