Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 41 ยท Sound and Input

Buttons and Text Input Boxes in Pygame

Build clickable buttons with hover states and a text input box with a cursor, backspace and focus in Pygame, plus reusable widget classes you can drop in.

Pygame draws pixels and delivers events; it ships no buttons, sliders or text fields. Menus, name entry screens and settings dialogs are therefore yours to build, and the good news is that two small classes cover most needs: a button and a text input box.

Both widgets share a pattern: they own a Rect, they accept events through a handle_event method, and they draw themselves in a draw(surface) method. This lesson builds them step by step. The real Pygame versions are read-only, while the logic is tested live with headless pygame.Rect and plain Python.

The widget pattern

flowchart LR
  A["Event loop"] -->|"each event"| B["widget.handle_event(event)"]
  A -->|"each frame"| C["widget.update()"]
  A -->|"each frame"| D["widget.draw(screen)"]
  B --> E["returns True/False<br/>or calls a callback"]

Every widget has the same three entry points: handle events, update, draw.

Keeping this shape for all widgets means that a screen with ten widgets simply loops over a list and calls the same three methods.

A button with hover and click states

A button needs a rectangle, a label and three visual states: normal, hovered and pressed. Hover is checked from the mouse position each frame. A click is complete only when the mouse button is released while still over the button; that is how every desktop program behaves and it lets the player slide away to cancel.

Python
import pygame

class Button:
    def __init__(self, rect, text, font, on_click):
        self.rect = pygame.Rect(rect)
        self.text = text
        self.font = font
        self.on_click = on_click
        self.hover = False
        self.pressed = False

    def handle_event(self, event):
        if event.type == pygame.MOUSEMOTION:
            self.hover = self.rect.collidepoint(event.pos)
        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            self.pressed = self.rect.collidepoint(event.pos)
        elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
            if self.pressed and self.rect.collidepoint(event.pos):
                self.on_click()
            self.pressed = False

    def draw(self, surface):
        colour = (70, 130, 200)
        if self.pressed:
            colour = (40, 90, 160)
        elif self.hover:
            colour = (100, 160, 230)
        pygame.draw.rect(surface, colour, self.rect, border_radius=8)
        label = self.font.render(self.text, True, (255, 255, 255))
        surface.blit(label, label.get_rect(center=self.rect.center))

border_radius gives rounded corners in one argument. label.get_rect(center=...) places the text perfectly in the middle without any arithmetic.

Try it: the click logic

The logic has no drawing in it, so it runs here. We feed scripted mouse events into a copy of the button and watch which clicks count.

Python When does a button click count?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Only the first and last pairs count. Releasing elsewhere cancels the click, and pressing elsewhere then releasing on the button does not trigger it either.

Using the button

Python
font = pygame.font.Font(None, 36)
state = {"running": True}

def quit_game():
    state["running"] = False

buttons = [
    Button((300, 200, 200, 50), "Play", font, lambda: print("start")),
    Button((300, 270, 200, 50), "Quit", font, quit_game),
]

while state["running"]:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quit_game()
        for b in buttons:
            b.handle_event(event)
    screen.fill((20, 24, 33))
    for b in buttons:
        b.draw(screen)
    pygame.display.flip()

Passing a function (on_click) keeps the button generic: it does not know what it does. A lambda is fine for small actions. A keyboard-friendly menu can also keep an index of the "selected" button and move it with the arrow keys; we do that in Game States and Menus.

A text input box

A text field is a small state machine: it is either focused or not, holds a string and (when focused) shows a blinking cursor. Characters arrive in KEYDOWN events through event.unicode.

Python
class TextBox:
    def __init__(self, rect, font, max_length=16):
        self.rect = pygame.Rect(rect)
        self.font = font
        self.text = ""
        self.focused = False
        self.max_length = max_length

    def handle_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            self.focused = self.rect.collidepoint(event.pos)
        elif event.type == pygame.KEYDOWN and self.focused:
            if event.key == pygame.K_BACKSPACE:
                self.text = self.text[:-1]
            elif event.key == pygame.K_RETURN:
                return self.text            # submit
            elif event.unicode.isprintable() and len(self.text) < self.max_length:
                self.text += event.unicode
        return None

    def draw(self, surface):
        border = (255, 220, 100) if self.focused else (140, 140, 160)
        pygame.draw.rect(surface, (30, 34, 46), self.rect, border_radius=6)
        pygame.draw.rect(surface, border, self.rect, 2, border_radius=6)
        img = self.font.render(self.text, True, (240, 240, 240))
        surface.blit(img, (self.rect.x + 8, self.rect.centery - img.get_height() // 2))
        if self.focused and (pygame.time.get_ticks() // 500) % 2 == 0:
            cx = self.rect.x + 8 + img.get_width() + 2
            pygame.draw.line(surface, (240, 240, 240),
                             (cx, self.rect.y + 8), (cx, self.rect.bottom - 8), 2)

Details worth noticing:

  • event.unicode is an empty string for keys like Shift or F5, and a control character ("\r", "\x08") for Enter and Backspace. isprintable() filters those out, though we handle Backspace and Return first.
  • The cursor blink uses get_ticks() // 500 % 2, a cheap square wave that is on for half a second, then off.
  • A max_length stops text from overflowing the box. For long text, measure with font.size(text)[0] and compare to the box width.

Try it: the editing logic

The string handling is plain Python. This stand-in replays key presses, including backspaces and a rejected character, through exactly the same rules.

Python Typing into a text box

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

"hellp" becomes "hell" and then "hello". The w fills the six-character limit ("hellow"), so the last o is rejected. The Shift key adds nothing because its unicode is empty.

Accessibility and polish

  • Let Tab move focus between fields, and Enter activate the focused button.
  • Show the hover colour and change the mouse cursor with pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_HAND) while over a button.
  • Make buttons big enough: height of 40 pixels or more.
  • Never rely on colour alone to show state. A border or an underline helps colour-blind players.
  • For text with accents or Asian languages, use the TEXTINPUT event, which supplies composed characters, instead of KEYDOWN.unicode.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When should a button's callback run?

    That matches how desktop buttons work and lets players cancel by sliding away before releasing.
  2. 2. How do you centre a rendered text surface inside a button rect?

    get_rect(center=...) returns a Rect positioned for you, which you pass to blit.
  3. 3. What does a blinking text cursor usually rely on?

    get_ticks() // 500 % 2 is 0 or 1 and flips every half second.
  4. 4. Why filter with event.unicode.isprintable() in a text box?

    Keys like Shift give an empty string and Enter or Backspace give control characters; neither should be inserted.

Summary

  • Widgets share three methods: handle_event, update and draw.
  • A button clicks on mouse-up when both press and release happen on it; hover and pressed states give feedback.
  • Pass behavior into widgets as callbacks to keep them reusable.
  • A text box tracks focus, a string and a blinking cursor, and handles Backspace and Return explicitly.
  • Use TEXTINPUT for international text and keep controls large and accessible.

Next: Movement and Delta Time