Buttons and Clicks

So far, Tina the turtle has drawn pictures for us. Now let’s build something you can click! In Brython you can make buttons, boxes, and text — right here in the browser, using the same editor.

Two new ideas:

  • screen is your space to put things. You add a piece with screen.add(piece), and it appears in the box below your code.
  • from browser import html gives you the pieces to build with, like html.BUTTON("...") and html.H2("...").

You make a button do something with button.bind("click", ...) — that tells Python which function to run each time the button is clicked.

A button that says hi

Press Run, then click the button.

Every time you click, Python runs your say_hi function. Try changing the message it shows.

A click counter

This one remembers how many times you have clicked.

Ask the user a question

An html.INPUT() is a box the user can type into. Read what they typed with box.value.

You can also add several pieces in one line: screen.add(box, button, greeting).

Roll the dice 🎲

You can mix in everything you already know — like random.

That’s the whole idea: build a piece, add it to the screen with screen.add(...), and make it react to clicks. From here you could build a quiz, a calculator, or a little game — all in the browser, no extra tools needed.