Welcome to pygwidgets’ documentation!

pygwidgets is a collection of user interface widgets (e.g., buttons) written in Python for use with Pygame.

pygwidgets is pronounced as: “pig wijits”.

Developed by Irv Kalb - Irv at furrypants.com

Full documentation at: https://pygwidgets.readthedocs.io/en/latest/

Design notes:

The way that you use objects instantiated from all these classes is very similar:

  1. Instantiate before the big loop starts.

  2. Call the object’s “handleEvent” method every time through the event loop,

    passing in the current event (from Pygame).

    It will return False most of the time, but returns True when something exciting happens (for example, user clicks on a button).

  3. Call the “draw” method (with no arguments) to draw each widget.

I have tried to make consistent keyword parameter names across classes.

I have also tried to make consistent names for methods across classes For example “getValue” and “setValue” are available in most classes.

When instantiating objects from these classes, you typically only need to specify a few parameters. The rest will use reasonable default values, but you can change them using keyword arguments.

Each of the button widgets comes in two varieties:

Text widget that is drawn using the Python’s drawing tools.

Custom widget where the programmer supplies their own graphics for the widget.

For example, “TextButton” below builds a button from a user-supplied text string, whereas “CustomButton” is built to work with user-supplied custom images.

pygwidgets contains the following classes:

  • TextButton - a button built on the fly from a user-supplied text.
  • CustomButton - a button where you use your own images
  • TextCheckBox - a checkbox built on the fly from a user-supplied text.
  • CustomCheckBox - a checkbox where you use your images
  • TextRadioButton - a radio button built on the fly from a user-supplied text.
  • CustomRadioButton - a radio button where you use your images
  • DisplayText - a text field used just for output (display)
  • InputText - a text field intended for user input
  • Dragger - gives the ability to drag any screen object with the mouse
  • Image - simple display of an image at a location
  • ImageCollection - A collection of Images, any of which can be shown at one time
  • Animation - display a set number of images, each at its own rate
  • SpriteSheetAnimation - display an animation directly from a sprite sheet (one file made up of many images)
Many widgets also allow the use of a callback (a function or method to be called when an action happens)
Any widget that uses a callback can be set up like this:
def <callbackMethodName>(self, nickName)

When the appropriate action happens, the callback method will be called and the nickName will be passed If you don’t need the nickname, you can just ignore that parameter


Simplified BSD License:

Copyright 2017 Irv Kalb. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY Irv Kalb ‘’AS IS’’ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Irv Kalb OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Irv Kalb.


History:

5/26/20 Version 1.0.2
Rewrote PygButton to be a state machine - much cleaner Added __version__ and function getVersion()

4/26/20 Minor documentation changes for handleEvent in a few classes

Version 1.0 01/13/20

12/19 Added: moveX, moveY, moveXY, overlapsRect, overlapsObject to base PygWidget In Animations classes changed .play() to .start() (for consistency with Timer objects) Changed names of internal Animation states.

5/19 Added ability in ImageCollection to specify a loaded image (alternative for giving path to image)
Fixed conflict with “replace” in Image and ImageCollection classes.
4/19 Added the ability for Image and ImageCollection objects to use the empty string
to indicate that the object should show no image. Added Image and ImageCollection to recognize clicks by adding handleEvents method
7/18 Added ability for all appropriate widgets to allow an optional callBack
Changed “textButton” in Button, CheckBox, and RadioButton to “text” Change “label” to “nickname” in all widgets.

6/18 Added Animation and SpriteSheetAnimation

6/18 Added getRect (removed copy from Dragger and Image)
In TextButton, changed param ‘label’ to ‘text’ to avoid confusion with superclass
5/18 Added Image object. Allows you to set a loc and window at the instantiation.
That way, all you need to do to show the image is to call its draw method.
1/18 Changed Button->TexButton, CheckBox->TextCheckBox, RadioButton->TextRadioButton
Changed SetVisible->show, setInVisible->hide Created PygWidget base class, and have all classes inherit from it initializes and contains: nickname, visible, isEnabled
11/17 Added Dragger, changed main “surface” to “window” Irv Kalb
Changed ‘caption’ in the Button class to ‘nickname’, made it a positional parameter (instead of optional keyword param) Added ‘nickname’ and getNickname method to most classes Modified Button to grow to fit very long nicknames - defaults to minimum of 100 pixels. Added setPos to DisplayText
4/17 Version 1.1 by Irv Kalb
Renamed a few classes and methods, simplified the return of handleEvent in all classes
to be just True or False.
3/17 Version 1.0 by Irv Kalb
Combined Buttons, CheckBoxes, RadioButtons, and Text into a single file
1/17 Major rewrite by Irv Kalb
Split the code into Button class and CustomButton class (with a common superclass: PygWidgetsButton). Added appropriate parameters with reasonable defaults so each is easier to instantiate. Added soundOnClick
12/16 Modified by Irv Kalb
Add a default surface, so it is passed in once at creation. That way, calls to draw do not need to pass it in again.
8/14 Modified by Irv Kalb
Added a disabled state to all buttons

The code of the TextButton and CustomButton classes are based on the original “pygbutton” code developed by Al Sweigart. I kept the good stuff (and there was plenty of that!), added features (most importantly a disabled state), and removed some features that I didn’t feel were needed for the students in my classes.


Classes

Animation

class pygwidgets.Animation(window, loc, animTuplesList, autoStart=False, loop=False, nickname=None, callBack=None, nIterations=1)

Shows an animated sequence of images

Typical use:

  1. Create an Animation object with a list of animation tuples:

    myAnimation = pygwidgets.Animation(window, loc, animTuplesList)

    See below for details and optional parameters.

  2. If you want to allow clicking on the animation to start the animation playing,

    then you need to call the handleEvent method every time through the loop. Most of the time it will return False, but will return True when the animation is clicked on.

    if myAnimation.handleEvent(event):

    myAnimation.start() # tell animation to start playing when clicked on (or anything else)

  3. In your big loop, call the update method to allow the animation to update itself in every frame.

    It figures out when it is time to show the next image. It typically returns False, but will return True when the animation finishes. If you want to check for the end of the animation, you can check the returned value like this:

    if myAnimation.update():

    # Animation has finished. Do whatever you want to do here.

    Alternatively, if you specified a callBack, that function or method will be called when the animation is finished.

  4. At the bottom of your big loop, draw the animation:

    myAnimation.draw()

Parameters:
window - the window of the application for the draw method to draw into
loc - location of where the dragger image should be drawn
animTuplesList - list of tuples, where each tuple looks like this:
(<path to image>, <duration>, <optional offset>)
In most cases you will only need a path and a duration
If an optional offset is given, it is used as an offset from loc
Optional keyword parameters:
autoStart - should the animation start right away (default False)
loop - should the animation loop continuously (default False)
nickname - an internal name to refer to this animation (default None)
callBack - function or object.method to call when the animation finishes (default None)
nIterations - number of iterations (default 1)
disable()

Disables the current widget.

draw()

Draws the current frame of the animation

Should be called in every frame.

enable()

Set this widget enabled.

getEnabled()

Returns the enabled state.

getLoc()

Returns the location of this widget as a tuple of values (X,Y) .

getLoop()

Returns True if the animation is looping, otherwise False.

getNickname()

Returns the nickname associated with this widget.

getRect()

Returns the rect of this widget.

getVisible()

Returns the visible state.

handleEvent(eventObj)

This method should be called every time through the main loop.

Returns:
False - if no event happens. True - if the user clicks the animation to start it playing.
hide()

Make this widget invisible.

moveX(nPixels)

Move some number of pixels in the X direction

moveXY(nPixelsX, nPixelsY)

Move some number of pixels in the X and Y directions

moveY(nPixels)

Move some number of pixels in the Y direction

overlapsObject(oOther)

Returns True if the rect of this object overlaps with rect of another pygwidgets object

overlapsRect(otherRect)

Returns True if the rect object overlaps another rect

pause()

Pauses a playing animation. A subsequent call to play will continue where it left off.

setLoc(loc)

Sets a new location for this widget. loc is a tuple of X and Y values (X, Y) It also changes the rect of the widget

setLoop(trueOrFalse)

Sets a value telling the animation if it should loop or not.

Paramter:
trueOrFalse - True to loop, False to not loop.
show()

Make this widget visible.

start()

Starts an animation playing.

stop()

Stops a a playing animation. A subsequent call to play will start from the beginning.

update()

Updates the currently running animation.

This method should be called in every frame where you want an animation to run. Its job is to figure out if it is time to move onto the next image in the animation.

CustomButton

class pygwidgets.CustomButton(window, loc, up, down=None, over=None, disabled=None, soundOnClick=None, nickname=None, enterToActivate=False, callBack=None)

CustomButton creates a button using custom images.

Each CustomButton has four states: up, over, down, and disabled.

Typical use:

  1. Create a CustomButton - giving a location tuple - as (left, top) and up to four images, e.g.:

    myButton = pygwidgets.CustomButton(window, (500, 430),
    up=’images/ButtonUp.png’,
    down=’images/ButtonDown.png’,
    over=’images/ButtonOver.png’,
    disabled=’images/ButtonDisabled.png’)
  2. In your big loop, check for the button being clicked by calling its handleEvent method:

    if myButton.handleEvent(event): # When the button is clicked, this returns True

    # the button was clicked, do whatever you want here

  3. At the bottom of your big loop, draw the button:

    myButton.draw()

The up, down, over, and disabled images must all be the same size. Only the up image needs to be specified. If any of the others are left out, they will default to be a copy of the up surface.

Parameters:
window - the window to draw the button in
loc - a tuple specifying the position (upper left corner) for the button to be drawn.
up - a path to a file with the button’s up appearance.
Optional keyword parameters:
down - a path to a file with the button’s pushed down appearance.
over - a path to a file with the button’s appearance when the mouse is over it.
disabled - a path to a file with the button’s disabled appearance.
soundOnClick - a path to a sound effect file. Plays when the button is clicked (defaults to None)
nickname - any name you want to use to identify this button (default is None)
callBack - a function or object.method to call when the button is clicked (default is None)
disable()

Disables the current widget.

draw()

Draws the button image based on its current state.

Should be called every time through the main loop

enable()

Set this widget enabled.

getEnabled()

Returns the enabled state.

getLoc()

Returns the location of this widget as a tuple of values (X,Y) .

getNickname()

Returns the nickname associated with this widget.

getRect()

Returns the rect of this widget.

getVisible()

Returns the visible state.

handleEvent(eventObj)

This method should be called every time through the main loop.

It handles showing the up, over, and down images of the button.

Parameters:
eventObj - the event object obtained by calling pygame.event.get()
Returns:
False most of the time
True when the user clicks down and later up on the button.
hide()

Make this widget invisible.

moveX(nPixels)

Move some number of pixels in the X direction

moveXY(nPixelsX, nPixelsY)

Move some number of pixels in the X and Y directions

moveY(nPixels)

Move some number of pixels in the Y direction

overlapsObject(oOther)

Returns True if the rect of this object overlaps with rect of another pygwidgets object

overlapsRect(otherRect)

Returns True if the rect object overlaps another rect

setLoc(loc)

Sets a new location for this widget. loc is a tuple of X and Y values (X, Y) It also changes the rect of the widget

show()

Make this widget visible.

CustomCheckBox

class pygwidgets.CustomCheckBox(window, loc, on, off, value=False, onDown=None, offDown=None, onDisabled=None, offDisabled=None, soundOnClick=None, nickname=None, callBack=None)

CustomCheckBox creates a checkbox with custom images.

Each CustomCheckBox has six states: on, off, onDown, offDown, onDisabled, offDisabled

Only the on and off states need to be specified. If left out, the others will default to be a copy of the on and off images.

Typical use:

  1. Create a CustomCheckBox - giving a location tuple - as (left, top) and at least two images:

    myCheckBox = pygwidgets.CustomButton(window, (500, 430), on=’images/CheckBoxOn.png’,

    off=’images/CheckBoxDown.png’, value=True)

  2. In your big loop, check for the button being clicked by calling its handleEvent method:

    if myCheckBox.handleEvent(event): # When clicked on to toggle, this returns True

    # CheckBox was clicked, do whatever you want here

  3. At the bottom of your big loop, draw the checkBox:

    myCheckBox.draw()

Parameters:
window - the window to draw the checkbox in
loc - a tuple specifying the position (upper left corner) for where the checkBox should be drawn.
on - a path to a file with the checkBox’s on appearance.
off - a path to a file with the checkBox’s off appearance.
Optional keyword parameters:
value = True for on, False for off (defaults to False)
onDown - a path to a file with the checkBox’s appearance when the user has clicked on the on image.
offDown - a path to a file with the checkBox’s appearance when the user has clicked on the off image.
onDisabled - a path to a file with the checkBox’s on appearance when not clickable.
offDisabled - a path to a file with the checkBox’s of appearance not clickable.
soundOnClick - a path to a sound effects file. Plays when the button is clicked (defaults to None)
nickname - Any nickname you want to use to identify this button (default is None)
callBack - a function or object.method to call when the button is clicked (default is None)
disable()

Disables the current widget.

draw()

Draws the checkbox.

enable()

Set this widget enabled.

getEnabled()

Returns the enabled state.

getLoc()

Returns the location of this widget as a tuple of values (X,Y) .

getNickname()

Returns the nickname associated with this widget.

getRect()

Returns the rect of this widget.

getValue()

Returns the value of the checkbox (True/False).

getVisible()

Returns the visible state.

handleEvent(eventObj)

This method should be called every time through the main loop.

It handles showing the up, over, and down states of the button.

Parameters:
eventObj - the event object obtained by calling pygame.event.get()
Returns:
False most of the time
True when the has toggled the checkbox.
hide()

Make this widget invisible.

moveX(nPixels)

Move some number of pixels in the X direction

moveXY(nPixelsX, nPixelsY)

Move some number of pixels in the X and Y directions

moveY(nPixels)

Move some number of pixels in the Y direction

overlapsObject(oOther)

Returns True if the rect of this object overlaps with rect of another pygwidgets object

overlapsRect(otherRect)

Returns True if the rect object overlaps another rect

setLoc(loc)

Sets a new location for this widget. loc is a tuple of X and Y values (X, Y) It also changes the rect of the widget

setValue(trueOrFalse)

Sets a new value for the checkBox to the value passed in.

show()

Make this widget visible.

CustomRadioButton

class pygwidgets.CustomRadioButton(window, loc, group, on, off, value=False, onDown=None, offDown=None, onDisabled=None, offDisabled=None, soundOnClick=None, nickname=None, callBack=None)

Creates a custom radio button - using custom images.

CustomRadioButton is a class that allows the user to specify their own images for a radio button.

Each CustomRadioButton has up to six states: on, off, onDown, offDown, onDisabled, offDisabled

Only the on and off states need to be specified. If left out, the others will default to copies of the on and off surfaces.

Typical use:

  1. Create a CustomRadioButton - giving a window, loc as (left, top), a group, and path to two images (on and off):

    myRadioButton = pygwidgets.CustomButton(window, (500, 430), ‘MyRadioButtonGroup’,

    ‘images/CheckBoxOn.png’, ‘images/CheckBoxDown.png’)

  2. In your big loop, check for the radioButton being clicked by calling its handleEvent method:

    if myRadioButton.handleEvent(event): # When clicked on to select, this returns True

    # RadioButton was clicked, do whatever you want here

  3. At the bottom of your big loop, draw the radioButton:

    myRadioButton.draw()

Parameters:
window - the window to draw the radio button in
loc - a tuple specifying the position (upper left corner) for where the radioButton should be drawn.
group - a name for the group that this radio button belongs to
(all radio buttons in the group need to use the same group name)
on - a path to a file with the radioButton’s on appearance.
off - a path to a file with the radioButton’s off appearance.
Optional keyword parameters:
value - True for selected, False for not selected (defaults to False)
onDown - a path to the file with the radioButton’s on down appearance. (defaults to copy of on)
offDown - a path to the file withthe radioButton’s off down appearance.(defaults to copy of off)
onDisabled - a path to a file with the radioButton’s on appearance when not clickable. (defaults to copy of on)
offDisabled - a path to a file with the radioButton’s of appearance not clickable. (defaults to copy of off)
soundOnClick - a path to a sound effects file. Plays when the button is clicked (defaults to None)
nickname - a nickname, which is returned when querying (see getSelectedRadioButton)
callBack - a function or object.method that is called when this item is clcked
disable(allInGroup=False)

Disables the current radio button

disableGroup()

Disables all radio buttons in the group

draw()

Draws the current state of the radio button.

enable(allInGroup=False)

Enable the current radio button.

enableGroup()

Enables all radio buttons in the group.

getEnabled()

Returns the enabled state.

getLoc()

Returns the location of this widget as a tuple of values (X,Y) .

getNickname()

Returns the nickname associated with this widget.

getRect()

Returns the rect of this widget.

getSelectedRadioButton()

Returns the nickname of the currently selected radio button.

getValue()

Returns the current value of the current radio button (True or False).

getVisible()

Returns the visible state.

handleEvent(eventObj)

This method should be called every time through the main loop.

It handles showing the up, over, and down states of the button.

Parameters:
eventObj - the event object obtained by calling pygame.event.get()
Returns:
False most of the time
True when the user selects a radio button from the group
hide()

Make this widget invisible.

moveX(nPixels)

Move some number of pixels in the X direction

moveXY(nPixelsX, nPixelsY)

Move some number of pixels in the X and Y directions

moveY(nPixels)

Move some number of pixels in the Y direction

overlapsObject(oOther)

Returns True if the rect of this object overlaps with rect of another pygwidgets object

overlapsRect(otherRect)

Returns True if the rect object overlaps another rect

setLoc(loc)

Sets a new location for this widget. loc is a tuple of X and Y values (X, Y) It also changes the rect of the widget

setValue(trueOrFalse)

Sets the value of the current radio button True or False.

show()

Make this widget visible.

DisplayText

class pygwidgets.DisplayText(window, loc=(0, 0), value='', fontName=None, fontSize=18, width=None, height=None, textColor=(0, 0, 0), backgroundColor=None, justified='left', nickname=None)

Create a field for displaying text.

Typical use:

  1. Create a DisplayText field:

    myDisplayText = pygwidgets.DisplayText(myWindow, (100, 200)) # Other optional arguments …

  2. Whenever you want to change the text to be displayed in your field,

    make this call to the setValue method:

    myDisplayText.setValue(‘Here is some new text to display’)

  3. To show the text field in your window, call the draw method every time through the main loop:

    myDisplayText.draw()

Parameters:
window - The window of the to draw the text into
loc - location of where the text should be drawn
Optional keyword parameters:
value - any initial text (defaults to the empty string)
fontName - name of font to use (defaults to None)
fontSize - size of font to use (defaults to 24)
width - width of the input text field (defauls to with of text to draw)
height - height of display text field (default to height of text to draw)
textColor - rgb color of the text (default to black)
backgroundColor - background rgb color of the text (defaults to white)
justified - ‘left’, ‘center’, or ‘right’ (defaults to ‘left’)
Note: If you want center or right justified, you probably want to specify a width value
(Otherwise, with a single text line, you will not see any difference)
nickname - a text name to refer to this object (defaults to None)

Inspired by a similar module written by David Clark (da_clark at shaw.ca) Changed parameters, defaults, methods to call, etc.

disable()

Disables the current widget.

draw()

Draws the current text in the window

enable()

Set this widget enabled.

getEnabled()

Returns the enabled state.

getLoc()

Returns the location of this widget as a tuple of values (X,Y) .

getNickname()

Returns the nickname associated with this widget.

getRect()

Returns the rect of this widget.

getText()

older name, now use getValue instead

getTextImage()

Returns the current text image

getValue()

Returns the text entered by the user

getVisible()

Returns the visible state.

hide()

Make this widget invisible.

moveX(nPixels)

Move some number of pixels in the X direction

moveXY(nPixelsX, nPixelsY)

Move some number of pixels in the X and Y directions

moveY(nPixels)

Move some number of pixels in the Y direction

overlapsObject(oOther)

Returns True if the rect of this object overlaps with rect of another pygwidgets object

overlapsRect(otherRect)

Returns True if the rect object overlaps another rect

setLoc(loc)

Sets a new location for this widget. loc is a tuple of X and Y values (X, Y) It also changes the rect of the widget

setText(newText)

older name, keeping this for older code that used it, now use setValue

setValue(newText)

Sets a text value (string) into the text field.

show()

Make this widget visible.

Dragger

class pygwidgets.Dragger(window, loc, up, down=None, over=None, disabled=None, nickname=None, callBack=None)

Dragger - Allows the user to drag an object around in the window.

Typical use:

  1. Create a Dragger:

    myDragger= pygwidgets.Dragger(myWindow, (100, 200), ‘images/DragMe.png’) # Other optional arguments …

  2. In your big while loop, call the ‘handleEvent’ method of the Dragger object(s)

    It will return False most of the time, and will return True when the user presses and lifts up on the mouse Here is the typical code to use:

    if myDragger.handleEvent(event):

    # print(‘Done dragging’) # do whatever you want here # Could call inherited getRect where dragger was released (and check if it is over a target)

  3. To show the dragger in your window, the typical code is to call the draw method:

    myDragger.draw()

Parameters:
window - the window of the application for the draw method to draw into
loc - location of where the dragger image should be drawn
up - path to up image
Optional keyword parameters:
down - path to down image
over - path to over image
disabled - path to disabled image
nickname - any nickname you want to use to identify this dragger
callback - a function or method of an object to call back when done dragging.
disable()

Disables the current widget.

draw()

Draws the dragger at the current mouse location.

Should be called in every frame.

enable()

Set this widget enabled.

getEnabled()

Returns the enabled state.

getLoc()

Returns the location of this widget as a tuple of values (X,Y) .

getMouseUpLoc()

Returns the location when the user let up on the mouse button.

getNickname()

Returns the nickname associated with this widget.

getRect()

Returns the rect of this widget.

getVisible()

Returns the visible state.

handleEvent(eventObj)

This method should be called every time through the main loop.

It handles all of the dragging

Parameters:
eventObj - the event object obtained by calling pygame.event.get()
Returns:
False most of the time
True when the user finishes dragging by lifting up on the mouse.
hide()

Make this widget invisible.

moveX(nPixels)

Move some number of pixels in the X direction

moveXY(nPixelsX, nPixelsY)

Move some number of pixels in the X and Y directions

moveY(nPixels)

Move some number of pixels in the Y direction

overlapsObject(oOther)

Returns True if the rect of this object overlaps with rect of another pygwidgets object

overlapsRect(otherRect)

Returns True if the rect object overlaps another rect

resetToPreviousLoc()

Resets the loc of the dragger to place where dragging started.

This could be used in a test situation if the dragger was dragged to an incorrect location.

setLoc(loc)

Sets a new location for this widget. loc is a tuple of X and Y values (X, Y) It also changes the rect of the widget

show()

Make this widget visible.

Image

class pygwidgets.Image(window, loc, pathOrLoadedImage, nickname=None)

Image - Show an image at a given location.

Typical use:

  1. Create an Image object:

    myImage = pygwidgets.Image(myWindow, (100, 200), ‘images/SomeImage.png’)

    You can call the inherited getRect tmethod o get the rectangle of the image

  2. To show the Image in your window, the typical code is to call the draw method:

    myImage.draw()

Parameters:
window - The window of the application so the draw method can draw into
loc - location of where the image should be drawn
pathOrLoadedImage - path to the image (string), or an image already loaded with pygame.image.load
Optional keyword parameters:
nickname - any nickname you want to use to identify this image
disable()

Disables the current widget.

draw()

Draws the image at the given location.

enable()

Set this widget enabled.

flipHorizontal()

flips an image object horizontally

flipVertical()

flips an image object vertically

getEnabled()

Returns the enabled state.

getLoc()

Returns the location of this widget as a tuple of values (X,Y) .

getNickname()

Returns the nickname associated with this widget.

getRect()

Returns the rect of this widget.

getVisible()

Returns the visible state.

handleEvent(event)

If you want to check for a click, this method should be called every time through the main loop.

It checks to see if the user has done a mouse down on the image.

Parameters:
eventObj - the event object obtained by calling pygame.event.get()
Returns:
False most of the time
True when the user clicks down on the image.
hide()

Make this widget invisible.

moveX(nPixels)

Move some number of pixels in the X direction

moveXY(nPixelsX, nPixelsY)

Move some number of pixels in the X and Y directions

moveY(nPixels)

Move some number of pixels in the Y direction

overlapsObject(oOther)

Returns True if the rect of this object overlaps with rect of another pygwidgets object

overlapsRect(otherRect)

Returns True if the rect object overlaps another rect

replace(newPathOrImage)

replace the image with a different image.

Parameters:
newPathOrImage - the path to the replacement image to show
if you specify the empty string(‘’), the image will go away
rotate(nDegrees)

rotates the image a given number of degrees

Parameters:
nDegrees - the number of degrees you want the image rotated (images start at zero degrees).
Positive numbers are clockwise, negative numbers are counter-clockwise
rotateTo(angle)

rotates the image to a given angle

Parameters:
angle - the angle that you want the image rotated to.
Positive numbers are clockwise, negative numbers are counter-clockwise
scale(percent, scaleFromCenter=True)

scales an Image object

Parameters:
percent - a percent of the original size
numbers bigger than 100 scale up
numbers less than 100 scale down
100 scales to the original size
Optional keyword parameters:
scaleFromCenter - should the image scale from the center or from the upper left hand corner
(default is True, scale from the center)
setLoc(loc)

Sets a new location for this widget. loc is a tuple of X and Y values (X, Y) It also changes the rect of the widget

show()

Make this widget visible.

ImageCollection

class pygwidgets.ImageCollection(window, loc, imagesDict, startImageKey, path='', nickname=None)

ImageCollection - Show an image chosen from a collection of images.

Typical use:

  1. Create a ImageCollection object:

    myImage = pygwidgets.ImageCollection(myWindow, (100, 200),

    {‘image1’:’images/SomeImage.png’, ‘image2’:’images/Image2.png’, ‘image3’:’images/Image3.png’}, ‘image1’)

    or

    myImage = pygwidgets.ImageCollection(myWindow, (100, 200),

    {‘image1’:’SomeImage.png’, ‘image2’:’Image2.png’, ‘image3’:’Image3.png’}, ‘image1’, path=’images/’)

  2. To display a different image, call the replace method, and specify the key of the image to display:

    myImage.replace(‘image2’)

  3. To draw the current image in your window, call the draw method:

    myImage.draw()

Parameters:
window - The window of the application so the draw method can draw into
loc - location of where the image should be drawn
dictOfImages - dictionary of key/value pairs of paths to different images
Each value in the dictionary can be either a path or an image already loaded with a call to pygame.load
A key of the empty string (‘’) is automaticaly added to the dictOfImages - use this key to make the image go away
startImageKey - the key of the first image to be drawn (This image will show until replace is called)
Optional keyword parameters:
path - any path that you want to prepend to each image for example,
if all images are in a folder, give the relative path to that folder
nickname - any nickname you want to use to identify this ImageCollection
disable()

Disables the current widget.

draw()

Draws the image at the given location.

enable()

Set this widget enabled.

flipHorizontal()

flips an image object horizontally

flipVertical()

flips an image object vertically

getEnabled()

Returns the enabled state.

getLoc()

Returns the location of this widget as a tuple of values (X,Y) .

getNickname()

Returns the nickname associated with this widget.

getRect()

Returns the rect of this widget.

getVisible()

Returns the visible state.

handleEvent(event)

If you want to check for a click, this method should be called every time through the main loop.

It checks to see if the user has done a mouse down on the image.

Parameters:
eventObj - the event object obtained by calling pygame.event.get()
Returns:
False most of the time
True when the user clicks down on the image.
hide()

Make this widget invisible.

moveX(nPixels)

Move some number of pixels in the X direction

moveXY(nPixelsX, nPixelsY)

Move some number of pixels in the X and Y directions

moveY(nPixels)

Move some number of pixels in the Y direction

overlapsObject(oOther)

Returns True if the rect of this object overlaps with rect of another pygwidgets object

overlapsRect(otherRect)

Returns True if the rect object overlaps another rect

replace(key)

Selects a different image to be shown.

Parameters:
key - a key in the original dictionary that specifies which image to show
rotate(nDegrees)

rotates the image a given number of degrees

Parameters:
nDegrees - the number of degrees you want the image rotated (images start at zero degrees).
Positive numbers are clockwise, negative numbers are counter-clockwise
rotateTo(angle)

rotates the image to a given angle

Parameters:
angle - the angle that you want the image rotated to.
Positive numbers are clockwise, negative numbers are counter-clockwise
scale(percent, scaleFromCenter=True)

scales an Image object

Parameters:
percent - a percent of the original size
numbers bigger than 100 scale up
numbers less than 100 scale down
100 scales to the original size
Optional keyword parameters:
scaleFromCenter - should the image scale from the center or from the upper left hand corner
(default is True, scale from the center)
setLoc(loc)

Sets a new location for this widget. loc is a tuple of X and Y values (X, Y) It also changes the rect of the widget

show()

Make this widget visible.

InputText

class pygwidgets.InputText(window, loc, value='', fontName=None, fontSize=24, width=200, textColor=(0, 0, 0), backgroundColor=(255, 255, 255), focusColor=(0, 0, 0), initialFocus=False, nickname=None, callBack=None, mask=None)

Creates a field where the user enter text (an editable field).

Typical use:

  1. Create an InputText field:

    myInputText = pygwidgets.InputText(myWindow, (100, 200)) # Other optional arguments …

  2. In your big while loop, call the ‘handleEvent’ method of the InputText object(s)

    It will return False most of the time, and will return True when the user presses RETURN or ENTER Here is the typical code to use:

    if myInputText.handleEvent(event):

    theText = myInputText.getValue() # call this method to get the text in the field # Do whatever you want with theText

  3. To show the text field in your window, call the draw method every time through the main loop:

    myInputText.draw()

Parameters:
window - the window to draw the text field in
loc - Location of where the text should be drawn
Optional keyword parameters:
value - any initial text (defaults to the empty string)
fontName - name of font to use (defaults to None)
fontSize - size of font to use (defaults to 24)
width - width of the input text field (defauls to 200 pixels)
textColor - rgb color of the text (default to black)
backgroundColor - background rgb color of the text (defaults to white)
focusColor - rgb color of a rectangle around the text when focused (defaults to black)
initialFocus - should this field have focus when at the beginning? (defaults to False)
Note: Only one field should have focus.
If more than one, all focused fields will get keys
mask - a character used to mask the text, typically set to asterisk for password field (defaults to None)
clearText(keepFocus=False)

Clear the text in the field

disable()

Disables the current widget.

draw()

Draws the Text in the window.

enable()

Set this widget enabled.

getEnabled()

Returns the enabled state.

getLoc()

Returns the location of this widget as a tuple of values (X,Y) .

getNickname()

Returns the nickname associated with this widget.

getRect()

Returns the rect of this widget.

getText()

older name, now use getValue instead

getTextImage()

Returns the image of the text.

getValue()

Returns the text entered by the user

getVisible()

Returns the visible state.

handleEvent(event)

This method should be called every time through the main loop.

It handles all of the keyboard key actions

Parameters:
eventObj - the event object obtained by calling pygame.event.get()
Returns:
False most of the time
True when the user presses Enter (Windows) or Return (Mac)
hide()

Make this widget invisible.

moveX(nPixels)

Move some number of pixels in the X direction

moveXY(nPixelsX, nPixelsY)

Move some number of pixels in the X and Y directions

moveY(nPixels)

Move some number of pixels in the Y direction

overlapsObject(oOther)

Returns True if the rect of this object overlaps with rect of another pygwidgets object

overlapsRect(otherRect)

Returns True if the rect object overlaps another rect

removeFocus()

Remove typing focus from this field.

Might want to call this (and getValue above), if there is some button to say user has finished typing

setLoc(loc)

Sets a new location for this widget. loc is a tuple of X and Y values (X, Y) It also changes the rect of the widget

setText(newText)

older name, keeping this for older code that used it, now use setValue

setValue(newText)

Sets new text into the field

show()

Make this widget visible.

SpriteSheetAnimation

class pygwidgets.SpriteSheetAnimation(window, loc, imagePath, nCols, nImages, width, height, durationOrDurationsList, autoStart=False, loop=False, nickname=None, callBack=None, nIterations=1)

SpriteSheetAnimation. Use with a single file containing multiple images.

Typical use:

  1. Create SpriteSheetAnimation specifying a number of parameters:

    myAnimation = pygwidgets.SpriteSheetAnimation(

    window, loc, imagePath, nCols, nImages, width, height, durationPerImage)

    See below for details and optional parameters.

  2. If you want to allow clicking on the animation to start the animation playing,

    then you need to call the handleEvent method every time through the loop. Most of the time it will return False, but will return True when the animation is clicked on

    if myAnimation.handleEvent(event):

    myAnimation.start() # tell animation to start playing when clicked on (or anything else)

  3. In your big loop, call the update method to allow the animation to update itself in every frame.

    It figures out when it is time to show the next image. It typically returns False, but will return True when the animation finishes. If you want to check for the end of the animation, you can check the returned value like this:

    if myAnimation.update():

    # Animation has finished. Do whatever you want to do here.

    Alternatively, if you specified a callBack, that function or method will be called when the animation is finished.

  4. At the bottom of your big loop, draw the animation:

    myAnimation.draw()

Parameters:
window - the window of the application for the draw method to draw into
loc - location of where the dragger image should be drawn
imagePath - path to the file containing multiple images
nCols - number of columns in the single file
nImages - total number of images in the single file
width - width of each individual image
height = height of each individual image
durationOrDurationsList - two options:
If a single value, then all images will use this duration
If a list or tuple, duration to show each image.
Optional keyword parameters:
autoStart - should the animation start right away (default False)
loop - should the animation loop continuously (default False)
nickname - an internal name to refer to this animation (default None)
callBack - function or object.method to call when the animation finishes (default None)
nIterations - number of iterations (default 1)
disable()

Disables the current widget.

draw()

Draws the current frame of the animation

Should be called in every frame.

enable()

Set this widget enabled.

getEnabled()

Returns the enabled state.

getLoc()

Returns the location of this widget as a tuple of values (X,Y) .

getLoop()

Returns True if the animation is looping, otherwise False.

getNickname()

Returns the nickname associated with this widget.

getRect()

Returns the rect of this widget.

getVisible()

Returns the visible state.

handleEvent(eventObj)

This method should be called every time through the main loop.

Returns:
False - if no event happens. True - if the user clicks the animation to start it playing.
hide()

Make this widget invisible.

moveX(nPixels)

Move some number of pixels in the X direction

moveXY(nPixelsX, nPixelsY)

Move some number of pixels in the X and Y directions

moveY(nPixels)

Move some number of pixels in the Y direction

overlapsObject(oOther)

Returns True if the rect of this object overlaps with rect of another pygwidgets object

overlapsRect(otherRect)

Returns True if the rect object overlaps another rect

pause()

Pauses a playing animation. A subsequent call to play will continue where it left off.

setLoc(loc)

Sets a new location for this widget. loc is a tuple of X and Y values (X, Y) It also changes the rect of the widget

setLoop(trueOrFalse)

Sets a value telling the animation if it should loop or not.

Paramter:
trueOrFalse - True to loop, False to not loop.
show()

Make this widget visible.

start()

Starts an animation playing.

stop()

Stops a a playing animation. A subsequent call to play will start from the beginning.

update()

Updates the currently running animation.

This method should be called in every frame where you want an animation to run. Its job is to figure out if it is time to move onto the next image in the animation.

TextButton

class pygwidgets.TextButton(window, loc, text, width=None, height=40, textColor=(0, 0, 0), upColor=(170, 170, 170), overColor=(210, 210, 210), downColor=(140, 140, 140), fontName=None, fontSize=20, soundOnClick=None, enterToActivate=False, callBack=None, nickname='')

TextButton creates a text-based button on the fly using a given string.

Each TextButton has four states: up, over, down, and disabled

Typical use:

  1. Create TextButton (giving a loc (left, top) and text). e.g.:

    myButton = pygwidgets.TextButton(window, (500, 430), ‘Some Text to show on the button’)

    There are many optional parameters, including width and height that have good defaults.

  2. In your big loop, check for the button being clicked by calling its handleEvent method:

    if myButton.handleEvent(event): # When the button is clicked, this returns True

    # the button was clicked, do whatever you want here

  3. At the bottom of your big loop, draw the button:

    myButton.draw()

Parameters:
window - the window to draw the button in
loc - the location (left and top) of the button as a tuple e.g. (10, 200).
text - the text to show on the button
Optional keyword parameters:
width - the width of the button (default is 100)
height - the height of the button (default is 40)
textColor - the rgb color of the text. (default is black).
upColor - the background rgb color of the up button (default is a medium gray)
overColor - the background rgb color of the over button (default is a lighter gray)
downColor - the background rgb color of down button (default is a darker gray)
fontName - the name of the font to use for the text (default is freesansbold)
fontsize - the size fo the font to use (default is 14)
soundOnClick - a path to a sound effect file. Plays when the button is clicked (defaults to None)
enterToActivate - if user presses Enter (or Return), button will activate (default is False)
nickname - any name you want to use to identify this button (default is None)
callBack - a function or object.method to call when the button is clicked (default is None)
disable()

Disables the current widget.

draw()

Draws the button image based on its current state.

Should be called every time through the main loop

enable()

Set this widget enabled.

getEnabled()

Returns the enabled state.

getLoc()

Returns the location of this widget as a tuple of values (X,Y) .

getNickname()

Returns the nickname associated with this widget.

getRect()

Returns the rect of this widget.

getVisible()

Returns the visible state.

handleEvent(eventObj)

This method should be called every time through the main loop.

It handles showing the up, over, and down images of the button.

Parameters:
eventObj - the event object obtained by calling pygame.event.get()
Returns:
False most of the time
True when the user clicks down and later up on the button.
hide()

Make this widget invisible.

moveX(nPixels)

Move some number of pixels in the X direction

moveXY(nPixelsX, nPixelsY)

Move some number of pixels in the X and Y directions

moveY(nPixels)

Move some number of pixels in the Y direction

overlapsObject(oOther)

Returns True if the rect of this object overlaps with rect of another pygwidgets object

overlapsRect(otherRect)

Returns True if the rect object overlaps another rect

setLoc(loc)

Sets a new location for this widget. loc is a tuple of X and Y values (X, Y) It also changes the rect of the widget

show()

Make this widget visible.

TextCheckBox

class pygwidgets.TextCheckBox(window, loc, text='', value=True, size=16, edgeColor=(0, 0, 0), insideColor=(255, 255, 255), insideDownColor=(210, 210, 210), textColor=(0, 0, 0), soundOnClick=None, nickname=None, callBack=None)

Builds a checkbox with a default text appearance.

Each TextCheckBox has six states: on, off, onDown, offDown, onDisabled, and offDisabled

Typical use:

  1. Create a TextCheckBox (giving a window and a loc (left, top)):

    myCheckBox = pygwidgets.TextCheckBox(window, (500, 430), True, ‘Text Nickname’)

    There are many optional parameters, that have good defaults.

  2. In your big loop, check for the button being clicked by calling its handleEvent method:

    if myCheckBox.handleEvent(event): # When clicked on to toggle, this returns True

    # CheckBox was clicked, do whatever you want here

  3. At the bottom of your big loop, draw the checkBox:

    myCheckBox.draw()

Parameters:
window - the window to draw the checkbox in
loc - a tuple specifying the upper left corner to draw the checkbox on the surface
Optional keyword parameters:
value - True for on, False for off (default is True)
size - used for both the width and the height (assuming a square box) - (default is 20 pixels)
edgeColor - the rgb color of the edges of the checkBox. (default is black)
insideColor = the rgb color of the inside of the checkBox. (default is white)
insideDownColor - the background rgb color of down button (default is a light gray)
textColor - the rgb color of the text word next to the checkbox (default is black)
soundOnClick - a path to a sound effect file. Plays when the checkbox is clicked (defaults to None)
nickname - any name you want to use to identify this button (default is None)
callBack - a function or object.method to call when the button is clicked (default is None)
disable()

Disables the current widget.

draw()

Draws the checkbox.

enable()

Set this widget enabled.

getEnabled()

Returns the enabled state.

getLoc()

Returns the location of this widget as a tuple of values (X,Y) .

getNickname()

Returns the nickname associated with this widget.

getRect()

Returns the rect of this widget.

getValue()

Returns the value of the checkbox (True/False).

getVisible()

Returns the visible state.

handleEvent(eventObj)

This method should be called every time through the main loop.

It handles showing the up, over, and down states of the button.

Parameters:
eventObj - the event object obtained by calling pygame.event.get()
Returns:
False most of the time
True when the has toggled the checkbox.
hide()

Make this widget invisible.

moveX(nPixels)

Move some number of pixels in the X direction

moveXY(nPixelsX, nPixelsY)

Move some number of pixels in the X and Y directions

moveY(nPixels)

Move some number of pixels in the Y direction

overlapsObject(oOther)

Returns True if the rect of this object overlaps with rect of another pygwidgets object

overlapsRect(otherRect)

Returns True if the rect object overlaps another rect

setLoc(loc)

Sets a new location for this widget. loc is a tuple of X and Y values (X, Y) It also changes the rect of the widget

setValue(trueOrFalse)

Sets a new value for the checkBox to the value passed in.

show()

Make this widget visible.

TextRadioButton

class pygwidgets.TextRadioButton(window, loc, group, text, value=False, soundOnClick=None, nickname=None, callBack=None)

Creates a text radio button.

Each RadioButton has six states: on, off, onDown, offDown, onDisabled, offDisabled

Typical use:

  1. Create a RadioButton (giving a window, loc as (left, top), group):

    myRadioButton = pygwidgets.TextRadioButton(window, (500, 430), ‘MyRadioButtonGroup’)

    There are many optional parameters, that have good defaults.

  2. In your big loop, check for the radioButton being clicked by calling its handleEvent method:

    if myRadioButton.handleEvent(event): # When clicked on to select, this returns True

    # RadioButton was clicked, do whatever you want here

  3. At the bottom of your big loop, draw the radioButton:

    myRadioButton.draw()

Parameters:
window - the window to draw the radio button in
loc - a tuple specifying the position (upper left corner) for where the radioButton should be drawn.
group - a name for the group that this radio button belongs to
(all radio buttons in the group need to use the same group name)
Optional keyword parameters:
value - true for on, False for off (defaults to False)
soundOnClick - Aa path to a sound effect file. Plays when the button is clicked (defaults to None)
nickname - a nickname, which is returned when querying (see getSelectedRadioButton)
callBack - a function or object.method that is called when this item is clcked
disable(allInGroup=False)

Disables the current radio button

disableGroup()

Disables all radio buttons in the group

draw()

Draws the current state of the radio button.

enable(allInGroup=False)

Enable the current radio button.

enableGroup()

Enables all radio buttons in the group.

getEnabled()

Returns the enabled state.

getLoc()

Returns the location of this widget as a tuple of values (X,Y) .

getNickname()

Returns the nickname associated with this widget.

getRect()

Returns the rect of this widget.

getSelectedRadioButton()

Returns the nickname of the currently selected radio button.

getValue()

Returns the current value of the current radio button (True or False).

getVisible()

Returns the visible state.

handleEvent(eventObj)

This method should be called every time through the main loop.

It handles showing the up, over, and down states of the button.

Parameters:
eventObj - the event object obtained by calling pygame.event.get()
Returns:
False most of the time
True when the user selects a radio button from the group
hide()

Make this widget invisible.

moveX(nPixels)

Move some number of pixels in the X direction

moveXY(nPixelsX, nPixelsY)

Move some number of pixels in the X and Y directions

moveY(nPixels)

Move some number of pixels in the Y direction

overlapsObject(oOther)

Returns True if the rect of this object overlaps with rect of another pygwidgets object

overlapsRect(otherRect)

Returns True if the rect object overlaps another rect

setLoc(loc)

Sets a new location for this widget. loc is a tuple of X and Y values (X, Y) It also changes the rect of the widget

setValue(trueOrFalse)

Sets the value of the current radio button True or False.

show()

Make this widget visible.

Indices and tables