Pygame Widgets

A helper module for common widgets that may be required in developing applications with Pygame. It supports fully customisable buttons, collections of buttons, textboxes and sliders. If there are any widgets that you would like to see added, please create an issue!

NEW FEATURES

  • Dropdown: Select options from a list that appears when hovered over

  • Progress Bar: Shows a percentage of completeness, great for loading screens and health bars

  • Toggle: Allows switching between two values, great for settings

  • Animations: Create an animation that changes a widgets attributes over some time, running on a separate thread

Prerequisites

  • Python 3

  • Pygame 2.0.0

Installation

Ensure that Python 3 and pip are installed and added to your environment PATH.

python -m pip install pygame-widgets

Open a Python console and run the following command.

import pygame_widgets

If you receive no error, the installation was successful.

Usage

  • Common

  • Button

  • ButtonArray

  • TextBox

  • Slider

  • Dropdown

  • Animations

Common

Functionality common to all widgets

Mandatory Parameters

Note: Mandatory parameters must be supplied in order.

ParameterDescriptionType
winSurface to be displayed on.pygame.Surface
xX-coordinate of top left.int
yY-coordinate of top left.int
widthWidth of button in pixels.int
heightHeight of button in pixels.int

Button

A customisable button

Example Usage

import pygame
from pygame_widgets import Button

pygame.init()
win = pygame.display.set_mode((600, 600))

button = Button(
    win, 100, 100, 300, 150, text='Hello',
    fontSize=50, margin=20,
    inactiveColour=(255, 0, 0),
    pressedColour=(0, 255, 0), radius=20,
    onClick=lambda: print('Click')
)

run = True
while run:
    events = pygame.event.get()
    for event in events:
        if event.type == pygame.QUIT:
            pygame.quit()
            run = False
            quit()

    win.fill((255, 255, 255))

    button.listen(events)
    button.draw()

    pygame.display.update()

This button will be placed at (100, 100) with a width of 300 and a height of 150, display the text ‘Hello’ with font

size 50, leaving a margin of 20 and a radius of 20. When clicked, the button will change colour from red to green and '

Click’ will be printed to the console.

Optional Parameters

ParameterDescriptionTypeDefault
inactiveColourDefault colour when not pressed or hovered over.(int, int, int)(150, 150, 150)
pressedColourColour when pressed.(int, int, int)(100, 100, 100)
hoverColourColour when hovered over.(int, int, int)(125, 125, 125)
shadowDistanceDistance to projected shadow. Set to 0 if no shadow desired.int0
shadowColourColour of shadow(int, int, int)(210, 210, 180)
onClickFunction to be called when clicked.functionNone
onClickParamsParameters to be fed into onClick function.(*any)()
onReleaseFunction to be called when released.functionNone
onReleaseParamsParameters to be fed into onRelease function.(*any)()
textColourColour of text.(int, int, int)(0, 0, 0)
fontSizeSize of text.int20
textString to be displayed.str''
fontFont of text.pygame.font.FontCalibri
textHAlignHorizontal alignment of text. Can be 'centre', 'left' or 'right'.str'centre'
textVAlignVertical alignment of text. Can be 'centre', 'top' or 'bottom'.str'centre'
marginMinimum distance between text / image and edge.int20
imageImage to be displayed.pygame.SurfaceNone
imageHAlignHorizontal alignment of image. Can be 'centre', 'left' or 'right'.str'centre'
imageVAlignVertical alignment of image. Can be 'centre', 'top' or 'bottom'.str'centre'
radiusBorder radius. Set to half of width for circular button. Set to 0 for no radius.int0

ButtonArray

A collection of similar buttons

Example Usage

import pygame
from pygame_widgets import ButtonArray

pygame.init()
win = pygame.display.set_mode((600, 600))

buttonArray = ButtonArray(win, 50, 50, 500, 500, (2, 2),
                          border=100, texts=('1', '2', '3', '4')
                          )

run = True
while run:
    events = pygame.event.get()
    for event in events:
        if event.type == pygame.QUIT:
            pygame.quit()
            run = False
            quit()

    win.fill((255, 255, 255))

    buttonArray.listen(events)
    buttonArray.draw()

    pygame.display.update()

Mandatory Parameters

Note: Mandatory parameters must be supplied in order.

ParameterDescriptionType
shapeNumber of columns and rows of buttons (columns, rows).(int, int)

Optional Parameters

Note: Optional parameters of ButtonArray are similar to those of Button.

ParameterDescriptionTypeDefault
colourBackground colour of array.(int, int, int)(210, 210, 180)
borderThickness between buttons and between the edges of array and buttons.int10
topBorderThickness between top of array and top of button. Overrides border.intborder
bottomBorderThickness between bottom of array and bottom of button. Overrides border.intborder
leftBorderThickness between left of array and left of button. Overrides border.intborder
rightBorderThickness between right of array and right of button. Overrides border.intborder
separationThicknessThickness between buttons. Overrides border.intborder

TextBox

A box for text input or display

textbox

Example Usage

import pygame
from pygame_widgets import TextBox


def output():
    # Get text in the textbox
    print(textbox.getText())


pygame.init()
win = pygame.display.set_mode((1000, 600))

textbox = TextBox(win, 100, 100, 800, 80, fontSize=50,
                  borderColour=(255, 0, 0), textColour=(0, 200, 0),
                  onSubmit=output, radius=10, borderThickness=5)

run = True
while run:
    events = pygame.event.get()
    for event in events:
        if event.type == pygame.QUIT:
            pygame.quit()
            run = False
            quit()

    win.fill((255, 255, 255))

    textbox.listen(events)
    textbox.draw()

    pygame.display.update()

Optional Parameters

ParameterDescriptionTypeDefault
colourBackground colour.(int, int, int)(220, 220, 220)
textColourColour of text.(int, int, int)(0, 0, 0)
borderColourColour of border.(int, int, int)(0, 0, 0)
borderThicknessThickness of border.int3
radiusBorder radius. Set to 0 for no radius.int0
onSubmitFunction to be called when return / enter is pressed.functionNone
onSubmitParamsParameters to be fed into onSubmit function.(*any)()
placeholderTextText to be displayed when empty.str''
fontSizeSize of text.int20
fontFont of text.pygame.font.FontCalibri

Slider

A slider for discrete numeric value selection

slider

Example Usage

import pygame
from pygame_widgets import Slider, TextBox

pygame.init()
win = pygame.display.set_mode((1000, 600))

slider = Slider(win, 100, 100, 800, 40, min=0, max=99, step=1)
output = TextBox(win, 475, 200, 50, 50, fontSize=30)

run = True
while run:
    events = pygame.event.get()
    for event in events:
        if event.type == pygame.QUIT:
            pygame.quit()
            run = False
            quit()

    win.fill((255, 255, 255))

    slider.listen(events)
    slider.draw()

    output.setText(slider.getValue())

    output.draw()

    pygame.display.update()

As you can see, TextBox can be used to display text as well, by not calling its listen method.

Optional Parameters

ParameterDescriptionTypeDefault
minMinimum value of the slider (left).int or float0
maxMaximum value of the slider (right).int or float99
stepValue to increment by.int or float1
colourColour of slider.(int, int, int)(200, 200, 200)
handleColourColour of handle.(int, int, int)(0, 0, 0)
initialInitial value of the slider.int or floatAverage of min and max
handleRadiusRadius of handle.intheight / 1.3
curvedAdd curved ends to the slider.boolTrue
import pygame
from pygame_widgets import Button, Dropdown

pygame.init()
win = pygame.display.set_mode((400, 280))

dropdown = Dropdown(
    win, 120, 10, 100, 50, name='Select Color',
    choices=[
        'Red',
        'Blue',
        'Yellow',
    ],
    borderRadius=3, colour=pygame.Color('green'), values=[1, 2, 'true'], direction='down', textHAlign='left'
)


def print_value():
    print(dropdown.getSelected())


button = Button(
    win, 10, 10, 100, 50, text='Print Value', fontSize=30,
    margin=20, inactiveColour=(255, 0, 0), pressedColour=(0, 255, 0),
    radius=5, onClick=print_value, font=pygame.font.SysFont('calibri', 10),
    textVAlign='bottom'
)

run = True
while run:
    events = pygame.event.get()
    for event in events:
        if event.type == pygame.QUIT:
            pygame.quit()
            run = False
            quit()

    win.fill((255, 255, 255))

    dropdown.listen(events)
    dropdown.draw()
    button.listen(events)
    button.draw()

    pygame.display.update()

This is a classic dropdown, but with a twist: if you right-click on the top, it reset itself. To get the current value

of the dropdown, we use the getSelected() methods.

It returns:

  • None if nothing is selected

  • A string with the choice you selected if the optional arg value is not set

  • If the optional arg value is set, we return the value corresponding to the choice.

For the example above:

ChoiceValue
Red1
Blue2
Yellow3

Example

dropdown

Mandatory Parameters

Note: Mandatory parameters must be supplied in order.

ParameterDescriptionType
nameMain name of the dropdownstr
choicesChoices to displaylist of str

Optional Parameters

ParameterDescriptionTypeDefault
directionExpansion direction. Can be 'down', 'up', 'left' or 'right'.strdown
valuesoptional return value corresponding to the choices. Must be the same length as `choices`lista copy of choices
inactiveColourDefault colour when not pressed or hovered over.(int, int, int)(150, 150, 150)
pressedColourColour when pressed.(int, int, int)(100, 100, 100)
hoverColourColour when hovered over.(int, int, int)(125, 125, 125)
onClickFunction to be called when clicked.functionNone
onClickParamsParameters to be fed into onClick function.(*any)()
onReleaseFunction to be called when released.functionNone
onReleaseParamsParameters to be fed into onRelease function.(*any)()
textColourColour of text.(int, int, int)(0, 0, 0)
fontSizeSize of text.int20
fontFont of text.pygame.font.Fontsans-serif
textHAlignHorizontal alignment of text. Can be 'centre', 'left' or 'right'.str'centre'
borderColourColour of border.(int, int, int)(0, 0, 0)
borderThicknessThickness of border.int3
borderRadiusBorder radius. Set to 0 for no radius.int0

Animations

Create an animation by using the default Translate or Resize, inheriting from AnimationBase, or using AnimationBase

directly.

Example Usage

import pygame
from pygame_widgets import Button, Resize

pygame.init()
win = pygame.display.set_mode((600, 600))

button = Button(win, 100, 100, 300, 150)

animation = Resize(button, 3, 200, 200)
animation.start()

run = True
while run:
    events = pygame.event.get()
    for event in events:
        if event.type == pygame.QUIT:
            pygame.quit()
            run = False
            quit()

    win.fill((255, 255, 255))

    button.listen(events)
    button.draw()

    pygame.display.update()

Over 3 seconds, the width of the button was changed from 300 to 200 and its height from 150 to 200. Since it is

performed on a separate thread, the button is still able to function during the animation.

GitHub

https://github.com/AustL/PygameWidgets

Source: https://pythonawesome.com/a-module-for-common-widgets-that-may-be-required-in-developing-app-with-pygame/