Welcome to pygwidgets’ documentation!¶
Classes¶
Animation¶
- class pygwidgets.Animation(window, loc, animTuplesList, autoStart=False, loop=False, showFirstImageAtEnd=True, path='', nickname=None, callBack=None, nIterations=1)¶
Shows an animated sequence of images
Typical use:
Create an Animation object with a list of animation tuples:
myAnimation = pygwidgets.Animation(window, loc, animTuplesList)
See below for details and optional parameters.
- 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 event 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)
- 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.
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 intoloc - location of where the animation image should be drawnanimTuplesList - 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 durationThe duration is in seconds, e.g., 1 for one second, or .5 for half a secondIf 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)showFirstImageAtEnd - when an animation ends, show the first image again (default True)path - a path to be prepended to all file paths (default is the empty string)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)
- Raises:
- FileNotFoundError if a file at a given path cannot be found
- 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 the current animation image
- getVisible()¶
Returns the visible state.
- handleEvent(eventObj)¶
This method should be called every time through the event loop (inside the main loop).
- Returns:
- False - if no event happens on this widget.True - if the user clicks the animation (typically to start it playing).
- hide()¶
Make this widget invisible.
- moveX(nPixels)¶
Move some number of pixels in the X direction
- Parameter:
- nPixels - the number of pixels to move
- moveXY(nPixelsX, nPixelsY)¶
Move some number of pixels in the X and Y directions
- Parameters:
- nPixelsX - the number of pixels to move in the X directionnPixelsY - the number of pixels to move in the Y direction
- moveY(nPixels)¶
Move some number of pixels in the Y direction
- Parameter:
- nPixels - the number of pixels to move
- overlapsObject(oOther)¶
Checks for overlap of two pygwidgets objects
- Parameter:
- oOther - a second object to compare to
- Returns:
- True or False if the rect of this object overlaps with the rect of another pygwidgets object
- pause()¶
Pauses a playing animation. A subsequent call to play will continue where it left off.
- play()¶
Same as start()
- setCenteredLoc(loc)¶
- Sets a new location for this widget. loc is a tuple of X and Y values (X, Y)
But it sets the center of the image of this widget to the X,Y position It also changes the rect of the widget
- Parameter:
- loc - a tuple of X,Y coordinates
- 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
- Parameter:
- loc - a tuple of X,Y coordinates
- setLoop(trueOrFalse)¶
Sets a value telling the animation if it should loop or not.
- Parameter:
- 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 start will play 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.
This method typically returns False, but will return True when an animation ends (and it is not looping)
AnimationCollection¶
- class pygwidgets.AnimationCollection(window, loc, animationsTuplesDict, startAnimationKey, autoStart=False, loop=False, showFirstImageAtEnd=True, path='', nickname=None, callBack=None, nIterations=1)¶
AnimationCollection - Show an animation chosen from a collection of animations.
Typical use:
- Create an AnimationCollection object (first define some animation tuples):
- walkNorthTuple = ((‘images/walker/walkN0.png’, .2), (‘images/walker/walkN1.png’, .1),(‘images/walker/walkN2.png’, .2), (‘images/walker/walkN3.png’, .2),(‘images/walker/walkN4.png’, .1), (‘images/walker/walkN5.png’, .2))walkEastTuple = ((‘images/walker/walkE0.png’, .2), (‘images/walker/walkE1.png’, .1),(‘images/walker/walkE2.png’, .2), (‘images/walker/walkE3.png’, .2),(‘images/walker/walkE4.png’, .1), (‘images/walker/walkE5.png’, .2))walkWestTuple = ((‘images/walker/walkW0.png’, .2), (‘images/walker/walkW1.png’, .1),(‘images/walker/walkW2.png’, .2), (‘images/walker/walkW3.png’, .2),(‘images/walker/walkW4.png’, .1), (‘images/walker/walkW5.png’, .2))walkSouthTuple = ((‘images/walker/walkS0.png’, .2), (‘images/walker/walkS1.png’, .1),(‘images/walker/walkS2.png’, .2), (‘images/walker/walkS3.png’, .2),(‘images/walker/walkS4.png’, .1), (‘images/walker/walkS5.png’, .2))myAnimations = AnimationCollection(window, (10, 10),{SOUTH: walkSouthTuple,NORTH: walkNorthTuple,WEST: walkWestTuple,EAST: walkEastTuple},SOUTH,loop=True, autoStart=False)
- To display a different animation, call the replace method, and specify the key of the animation to display:
- myAnimations.replace(‘EAST’)
- To display the current animation in your window, call the draw method:
- myAnimation.draw()
- Parameters:
- window - The window of the application so the draw method can draw intoloc - location of where the image should be drawnanimationTuplesDict - dictionary of key/value pairs of animationsEach entry in the tuples list is a path and a time for that image to showstartImageKey - the key of the first animation to be drawn (This image will show until replace is called)
- Optional keyword parameters:
- path - any path that you want to prepend to each animation, for example,if all images are in a folder named ‘animations’, give the relative path to that folder as ‘animations/’ (defaults to empty string)nickname - any nickname you want to use to identify this AnimationCollection (defaults to None)
- Raises:
- ValueError if the startImageKey is not found in the animationsDict dictionaryFileNotFoundError if a file at a given path cannot be found
- 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 the current animation image
- getVisible()¶
Returns the visible state.
- handleEvent(eventObj)¶
This method should be called every time through the event loop (inside the main loop).
- Returns:
- False - if no event happens on this widget.True - if the user clicks the animation (typically to start it playing).
- hide()¶
Make this widget invisible.
- moveX(nPixels)¶
Move some number of pixels in the X direction
- Parameter:
- nPixels - the number of pixels to move
- moveXY(nPixelsX, nPixelsY)¶
Move some number of pixels in the X and Y directions
- Parameters:
- nPixelsX - the number of pixels to move in the X directionnPixelsY - the number of pixels to move in the Y direction
- moveY(nPixels)¶
Move some number of pixels in the Y direction
- Parameter:
- nPixels - the number of pixels to move
- overlapsObject(oOther)¶
Checks for overlap of two pygwidgets objects
- Parameter:
- oOther - a second object to compare to
- Returns:
- True or False if the rect of this object overlaps with the rect of another pygwidgets object
- pause()¶
Pauses a playing animation. A subsequent call to play will continue where it left off.
- play()¶
Same as start()
- replace(key)¶
Selects a different animation to be shown.
- Parameters:
- key - a key in the animations dictionary that specifies which animation to show
- Raises:
- KeyError if the key to use to replace an animation is not found in the dictionary
- setCenteredLoc(loc)¶
- Sets a new location for this widget. loc is a tuple of X and Y values (X, Y)
But it sets the center of the image of this widget to the X,Y position It also changes the rect of the widget
- Parameter:
- loc - a tuple of X,Y coordinates
- setLoc(locTuple)¶
- 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
- Parameter:
- loc - a tuple of X,Y coordinates
- setLoop(trueOrFalse)¶
Sets a value telling the animation if it should loop or not.
- Parameter:
- 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 start will play 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.
This method typically returns False, but will return True when an animation ends (and it is not looping)
BackgroundSound¶
- class pygwidgets.BackgroundSound(relativePath)¶
- BackgroundSound - allows you to play a long background file - typically music.
Each is typically a .mp3 file.
Typical use:
- Create a BackgroundSound object specifying a path to a music sound file (.mp3)
- musicSound = pygwidgets.BackgroundSound(‘sounds/myMusic.mp3’)
- To play the backgroundSound:
- musicSound.play()
- Parameters:
- relativePath - a relative path to the sound file
- Raises:
- FileNotFoundError if a file at a given path cannot be found
- getPlaying()¶
Returns True if the music is playing, or False if it is not
- pause()¶
If music is playing, pause the music
- play(nLoops=-1, start=0.0)¶
Starts the music playing (same as start)
- start(nLoops=-1, start=0.0)¶
Starts the music playing
- Parameters:
- nLoops - number of times to loop the music (default is -1 meaning continuously)start - how far into the music to start (default is 0.0 meaning start at the beginning)
- stop()¶
Stops the current music that is playing
- unPause()¶
If music is playing, but is paused, unpause the music to let it play again
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:
Create a CustomCheckBox - giving a location tuple - as (left, top) and at least two images:
- myCheckBox = pygwidgets.CustomCheckBox(window, (500, 430),
on=’images/CheckBoxOn.png’, off=’images/CheckBoxOff.png’, value=True)
In your event loop, check for the button being clicked by calling its handleEvent method:
- if myCheckBox.handleEvent(event): # When clicked to toggle, this returns True
# CheckBox was clicked, do whatever you want here
At the bottom of your big loop, draw the checkBox:
myCheckBox.draw()
- Parameters:
- window - the window to draw the checkbox inloc - 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 (defaults to None)offDown - a path to a file with the checkBox’s appearance when the user has clicked on the off image (defaults to None)onDisabled - a path to a file with the checkBox’s on appearance when not clickable (defaults to None)offDisabled - a path to a file with the checkBox’s of appearance not clickable (defaults to None)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)
- Raises:
- FileNotFoundError if a file at a given path cannot be found
- 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 event loop (inside 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 timeTrue when the user has toggled the checkbox.
- hide()¶
Make this widget invisible.
- moveX(nPixels)¶
Move some number of pixels in the X direction
- Parameter:
- nPixels - the number of pixels to move
- moveXY(nPixelsX, nPixelsY)¶
Move some number of pixels in the X and Y directions
- Parameters:
- nPixelsX - the number of pixels to move in the X directionnPixelsY - the number of pixels to move in the Y direction
- moveY(nPixels)¶
Move some number of pixels in the Y direction
- Parameter:
- nPixels - the number of pixels to move
- overlapsObject(oOther)¶
Checks for overlap of two pygwidgets objects
- Parameter:
- oOther - a second object to compare to
- Returns:
- True or False if the rect of this object overlaps with the rect of another pygwidgets object
- setCenteredLoc(loc)¶
- Sets a new location for this widget. loc is a tuple of X and Y values (X, Y)
But it sets the center of the image of this widget to the X,Y position It also changes the rect of the widget
- Parameter:
- loc - a tuple of X,Y coordinates
- 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
- Parameter:
- loc - a tuple of X,Y coordinates
- setValue(trueOrFalse)¶
Sets a new value for the checkBox to the value passed in.
- show()¶
Make this widget visible.
- toggleValue()¶
Switches the current value of a checkBox and returns the new value
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:
Create a DisplayText field:
myDisplayText = pygwidgets.DisplayText(myWindow, (100, 200)) # Other optional arguments …
- 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’)
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 intoloc - location of where the text should be drawn
- Optional keyword parameters:
- value - any initial text (defaults to the empty string)fontName - font to use for text, or font file, or None for system font (default is None)fontSize - size of font to use (defaults to 18)width - width of the input text field (defaults to width of text to draw)height - height of display text field (defaults to height of text to draw)textColor - rgb color of the text (default to black)backgroundColor - background rgb color of the text (defaults to None - transparent)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)
- Raises:
- ValueError if justified is not ‘left’, ‘center’, or ‘right’
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
- Parameter:
- nPixels - the number of pixels to move
- moveXY(nPixelsX, nPixelsY)¶
Move some number of pixels in the X and Y directions
- Parameters:
- nPixelsX - the number of pixels to move in the X directionnPixelsY - the number of pixels to move in the Y direction
- moveY(nPixels)¶
Move some number of pixels in the Y direction
- Parameter:
- nPixels - the number of pixels to move
- overlapsObject(oOther)¶
Checks for overlap of two pygwidgets objects
- Parameter:
- oOther - a second object to compare to
- Returns:
- True or False if the rect of this object overlaps with the rect of another pygwidgets object
- render()¶
Convert the text into an image so it can be drawn in the window. (Called by setValue.)
- setCenteredLoc(loc)¶
- Sets a new location for this widget. loc is a tuple of X and Y values (X, Y)
But it sets the center of the image of this widget to the X,Y position It also changes the rect of the widget
- Parameter:
- loc - a tuple of X,Y coordinates
- 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
- Parameter:
- loc - a tuple of X,Y coordinates
- setText(newText)¶
older name, keeping this for older code that used it, now use setValue
- setValue(newText)¶
Sets a text value (string or list/tuple) 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:
Create a Dragger:
myDragger= pygwidgets.Dragger(myWindow, (100, 200), ‘images/DragMe.png’) # Other optional arguments …
- In your event loop, call the handleEvent method of the Dragger object
It will return False most of the time, and will return True when the has pressed on this image 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)
To show the dragger in your window, call the draw method:
myDragger.draw()
- Parameters:
- window - the window of the application for the draw method to draw intoloc - location of where the dragger image should be drawnup - path to up image
Optional keyword parameters:
down - path to down image (defaults to None, copy of up image)over - path to over image (defaults to None, copy of up image)disabled - path to disabled image (defaults to None, copy of up image)nickname - any nickname you want to use to identify this dragger (defaults to None)callBack - a function or method of an object to call back when done dragging (defaults to None)- Raises:
- FileNotFoundError if a file at a given path cannot be found
- 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 event loop (inside 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 timeTrue 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
- Parameter:
- nPixels - the number of pixels to move
- moveXY(nPixelsX, nPixelsY)¶
Move some number of pixels in the X and Y directions
- Parameters:
- nPixelsX - the number of pixels to move in the X directionnPixelsY - the number of pixels to move in the Y direction
- moveY(nPixels)¶
Move some number of pixels in the Y direction
- Parameter:
- nPixels - the number of pixels to move
- overlapsObject(oOther)¶
Checks for overlap of two pygwidgets objects
- Parameter:
- oOther - a second object to compare to
- Returns:
- True or False if the rect of this object overlaps with the rect of another pygwidgets object
- 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.
- setCenteredLoc(loc)¶
- Sets a new location for this widget. loc is a tuple of X and Y values (X, Y)
But it sets the center of the image of this widget to the X,Y position It also changes the rect of the widget
- Parameter:
- loc - a tuple of X,Y coordinates
- 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
- Parameter:
- loc - a tuple of X,Y coordinates
- show()¶
Make this widget visible.
Image¶
- class pygwidgets.Image(window, loc, pathOrLoadedImage, nickname=None)¶
Image - Show an image at a given location.
Typical use:
Create an Image object:
myImage = pygwidgets.Image(myWindow, (100, 200), ‘images/SomeImage.png’)
You can call the inherited getRect method to get the rectangle of the image
(Optional) if you want to be able to check if the user clicked on an image, you can call handleEvent:
if myImage.handleEvent(eventObj): # will return True if the user clicks on it
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 intoloc - location of where the image should be drawnpathOrLoadedImage - path to the image (string), or an already loaded image
- Optional keyword parameters:
- nickname - any nickname you want to use to identify this image (defaults to None)
- Raises:
- FileNotFoundError if a file at a given path cannot be found
- 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.
- getFocus()¶
Returns True or False depending on if this Image has focus.
- 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 event loop.
It checks to see if the user has done a mouse down on the image.
- Parameters:
- event - the event object obtained by calling pygame.event.get()
- Returns:
- False most of the timeTrue when the user clicks down on the image.
- hide()¶
Make this widget invisible.
- moveX(nPixels)¶
Move some number of pixels in the X direction
- Parameter:
- nPixels - the number of pixels to move
- moveXY(nPixelsX, nPixelsY)¶
Move some number of pixels in the X and Y directions
- Parameters:
- nPixelsX - the number of pixels to move in the X directionnPixelsY - the number of pixels to move in the Y direction
- moveY(nPixels)¶
Move some number of pixels in the Y direction
- Parameter:
- nPixels - the number of pixels to move
- overlapsObject(oOther)¶
Checks for overlap of two pygwidgets objects
- Parameter:
- oOther - a second object to compare to
- Returns:
- True or False if the rect of this object overlaps with the rect of another pygwidgets object
- replace(newPathOrImage)¶
replace the image with a different image.
- Parameters:
- newPathOrImage - the path to the replacement image to showif 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 sizenumbers bigger than 100 scale upnumbers less than 100 scale down100 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)
- setCenteredLoc(loc)¶
- Sets a new location for this widget. loc is a tuple of X and Y values (X, Y)
But it sets the center of the image of this widget to the X,Y position It also changes the rect of the widget
- Parameter:
- loc - a tuple of X,Y coordinates
- 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
- Parameter:
- loc - a tuple of X,Y coordinates
- 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:
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/’)
To display a different image, call the replace method, and specify the key of the image to display:
myImage.replace(‘image2’)
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 intoloc - location of where the image should be drawnimagesDict - dictionary of key/value pairs of paths to different imagesEach value in the dictionary can be either a path or an image already loaded with a call to pygame.loadA key of the empty string (‘’) is automatically added to the dictOfImages - use this key to make the image go awaystartImageKey - 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 named ‘images’, give the relative path to that folder as ‘images/’ (defaults to empty string)nickname - any nickname you want to use to identify this ImageCollection (defaults to None)
- Raises:
- ValueError if the startImageKey is not found in the imagesDict dictionaryKeyError if a call to replace() contains a key that is not in the imagesDictFileNotFoundError if a file at a given path cannot be found
- 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
- getCurrentKey()¶
Returns the currently selected key in an ImageCollection
- getEnabled()¶
Returns the enabled state.
- getFocus()¶
Returns True or False depending on if this Image has focus.
- 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 event loop.
It checks to see if the user has done a mouse down on the image.
- Parameters:
- event - the event object obtained by calling pygame.event.get()
- Returns:
- False most of the timeTrue when the user clicks down on the image.
- hide()¶
Make this widget invisible.
- moveX(nPixels)¶
Move some number of pixels in the X direction
- Parameter:
- nPixels - the number of pixels to move
- moveXY(nPixelsX, nPixelsY)¶
Move some number of pixels in the X and Y directions
- Parameters:
- nPixelsX - the number of pixels to move in the X directionnPixelsY - the number of pixels to move in the Y direction
- moveY(nPixels)¶
Move some number of pixels in the Y direction
- Parameter:
- nPixels - the number of pixels to move
- overlapsObject(oOther)¶
Checks for overlap of two pygwidgets objects
- Parameter:
- oOther - a second object to compare to
- Returns:
- True or False if the rect of this object overlaps with the rect of another pygwidgets object
- replace(key)¶
Selects a different image to be shown.
- Parameters:
- key - a key in the original dictionary that specifies which image to show
- Raises:
- KeyError if the key to use to replace an image is not found in the dictionary
- 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 sizenumbers bigger than 100 scale upnumbers less than 100 scale down100 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)
- setCenteredLoc(loc)¶
- Sets a new location for this widget. loc is a tuple of X and Y values (X, Y)
But it sets the center of the image of this widget to the X,Y position It also changes the rect of the widget
- Parameter:
- loc - a tuple of X,Y coordinates
- 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
- Parameter:
- loc - a tuple of X,Y coordinates
- 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, keepFocusOnSubmit=False)¶
Creates a field where the user can enter text (an editable field).
Typical use:
Create an InputText field:
myInputText = pygwidgets.InputText(myWindow, (100, 200)) # Other optional arguments …
- In your event loop, call the ‘handleEvent’ method of the InputText object
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 the user typed in the field # Do whatever you want with theText
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 inloc - Location of where the text should be drawn
- Optional keyword parameters:
- value - any initial text (defaults to the empty string)fontName - font to use for text, or font file, or None for system font (default is None)fontSize - size of font to use (defaults to 24)width - width of the input text field (defaults 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 has focus, all focused fields will get keysnickname - an internal nickname for this object (defaults to None)callBack - a function or object.method to call back when user presses Enter or Return(defaults to None)mask - a character used to mask the text, typically set to asterisk for password field (defaults to None)keepFocusOnSubmit - when user presses Return/Enter should the field keep focus (defaults to False)
- 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.
- giveFocus()¶
Give focus to this field Make sure focus is removed from any previous field before calling this
- handleEvent(event)¶
This method should be called every time through the event loop (inside 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 timeTrue 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
- Parameter:
- nPixels - the number of pixels to move
- moveXY(nPixelsX, nPixelsY)¶
Move some number of pixels in the X and Y directions
- Parameters:
- nPixelsX - the number of pixels to move in the X directionnPixelsY - the number of pixels to move in the Y direction
- moveY(nPixels)¶
Move some number of pixels in the Y direction
- Parameter:
- nPixels - the number of pixels to move
- overlapsObject(oOther)¶
Checks for overlap of two pygwidgets objects
- Parameter:
- oOther - a second object to compare to
- Returns:
- True or False if the rect of this object overlaps with the rect of another pygwidgets object
- 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
- setCenteredLoc(loc)¶
- Sets a new location for this widget. loc is a tuple of X and Y values (X, Y)
But it sets the center of the image of this widget to the X,Y position It also changes the rect of the widget
- Parameter:
- loc - a tuple of X,Y coordinates
- setLoc(loc)¶
Move the field to some other location
- setNextFieldOnTab(oNextFieldOnTab)¶
Allows TAB key to move to a field of programmers choice
- Parameters:
- oNextFieldOnTab - an InputText object that should gain focus if user hits TAB
- 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.
SoundEffect¶
- class pygwidgets.SoundEffect(relativePath)¶
- SoundEffect - allows you to play a short sound effect.
Each is typically a .wav file.
Typical use:
- Create a SoundEffect object specifying a path to a sound effect file (.wav)
- crashSound = pygwidgets.SoundEffect(‘sounds/crash.wav’)
- To play the sound effect:
- crashSound.play()
- Parameters:
- relativePath - a relative path to the sound file
- Raises:
- FileNotFoundError if a file at a given path cannot be found
- play()¶
Starts the sound effect playing
SpriteSheetAnimation¶
- class pygwidgets.SpriteSheetAnimation(window, loc, imagePath, nImages, width, height, durationOrDurationsList, autoStart=False, loop=False, showFirstImageAtEnd=True, path='', nickname=None, callBack=None, nIterations=1)¶
SpriteSheetAnimation. Use with a single file containing multiple images.
Typical use:
- Create SpriteSheetAnimation specifying a number of parameters:
- myAnimation = pygwidgets.SpriteSheetAnimation(window, loc, imagePath, nImages, width, height, durationPerImage)See below for details and optional parameters.
- 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 event loop.Most of the time it will return False, but will return True when the animation is clicked onif myAnimation.handleEvent(event):myAnimation.start() # tell animation to start playing when clicked on (or anything else)
- 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 calledwhen the animation is finished.
- 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 intoloc - location of where the current animation image should be drawnimagePath - path to the file containing multiple imagesnImages - total number of images in the single filewidth - width of each individual imageheight = height of each individual imagedurationOrDurationsList - two options:If a single value, then all images will use this durationIf 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)showFirstImageAtEnd - when an animation ends, show the first image again (default True)path - a path to be prepended to all file paths (default is the empty string)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)
- Raises:
- ValueError if the number of images and the length of the durations list don’t matchFileNotFoundError if a file at a given path cannot be found
- 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 the current animation image
- getVisible()¶
Returns the visible state.
- handleEvent(eventObj)¶
This method should be called every time through the event loop (inside the main loop).
- Returns:
- False - if no event happens on this widget.True - if the user clicks the animation (typically to start it playing).
- hide()¶
Make this widget invisible.
- moveX(nPixels)¶
Move some number of pixels in the X direction
- Parameter:
- nPixels - the number of pixels to move
- moveXY(nPixelsX, nPixelsY)¶
Move some number of pixels in the X and Y directions
- Parameters:
- nPixelsX - the number of pixels to move in the X directionnPixelsY - the number of pixels to move in the Y direction
- moveY(nPixels)¶
Move some number of pixels in the Y direction
- Parameter:
- nPixels - the number of pixels to move
- overlapsObject(oOther)¶
Checks for overlap of two pygwidgets objects
- Parameter:
- oOther - a second object to compare to
- Returns:
- True or False if the rect of this object overlaps with the rect of another pygwidgets object
- pause()¶
Pauses a playing animation. A subsequent call to play will continue where it left off.
- play()¶
Same as start()
- setCenteredLoc(loc)¶
- Sets a new location for this widget. loc is a tuple of X and Y values (X, Y)
But it sets the center of the image of this widget to the X,Y position It also changes the rect of the widget
- Parameter:
- loc - a tuple of X,Y coordinates
- 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
- Parameter:
- loc - a tuple of X,Y coordinates
- setLoop(trueOrFalse)¶
Sets a value telling the animation if it should loop or not.
- Parameter:
- 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 start will play 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.
This method typically returns False, but will return True when an animation ends (and it is not looping)
SpriteSheetAnimationCollection¶
- class pygwidgets.SpriteSheetAnimationCollection(window, loc, spriteSheetAnimationsDict, startAnimationKey, autoStart=False, loop=False, showFirstImageAtEnd=True, path='', nickname=None, callBack=None, nIterations=1)¶
SpriteSheetAnimationCollection - Show an animation chosen from a collection of sprite sheet animations.
Typical use:
- First define a dictionary sprite sheet animation info. Each key value pair looks like this:
- <someKey>:(<imagePath>, <nImages>, <width>, <height>, <durationsOrDurationsList>)animationCollectionDict = {‘right’ : (‘images/runRight.png’,10, 30, 40, .1),‘left’ : (‘images/characters/runLeft.png’,10, 30, 40, .1)}Then create a SpriteSheetAnimationCollection object with multiple sprite sheet animationsmyAnimCollection = pygwidgets.SpriteSheetAnimationCollection(window, (50, 50),animationCollectionDict, ‘right’, autoStart=True, loop=True)
- To display a different animation, call the replace method, and specify the key of the animation to display:
- myAnimCollection.replace(‘left’)
- To display the current animation in your window, call the draw method:
- myAnimCollection.draw()
- Parameters:
- window - the window of the application for the draw method to draw intoloc - location of where the current animation image should be drawnspriteSheetAnimationsDict, a dictionary of animations where each key/value pair looks like:<someKey>:(<imagePath>, <nImages>, <width>, <height>, <durationsOrDurationsList>)This tuple must consist of 5 elements:imagePath - path to the file containing multiple images (element 0)nImages - total number of images in the single file (element 1)width - width of each individual image (element 2)height = height of each individual image (element 3)durationOrDurationsList (element 4) - two options:If a single value, then all images will use this durationIf 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)showFirstImageAtEnd - when an animation ends, show the first image again (default True)path - a path to be prepended to all file paths (default is the empty string)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)
- Raises:
- ValueError if the number of images and the length of the durations list don’t matchFileNotFoundError if a file at a given path cannot be found
- 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 the current animation image
- getVisible()¶
Returns the visible state.
- handleEvent(eventObj)¶
This method should be called every time through the event loop (inside the main loop).
- Returns:
- False - if no event happens on this widget.True - if the user clicks the animation (typically to start it playing).
- hide()¶
Make this widget invisible.
- moveX(nPixels)¶
Move some number of pixels in the X direction
- Parameter:
- nPixels - the number of pixels to move
- moveXY(nPixelsX, nPixelsY)¶
Move some number of pixels in the X and Y directions
- Parameters:
- nPixelsX - the number of pixels to move in the X directionnPixelsY - the number of pixels to move in the Y direction
- moveY(nPixels)¶
Move some number of pixels in the Y direction
- Parameter:
- nPixels - the number of pixels to move
- overlapsObject(oOther)¶
Checks for overlap of two pygwidgets objects
- Parameter:
- oOther - a second object to compare to
- Returns:
- True or False if the rect of this object overlaps with the rect of another pygwidgets object
- pause()¶
Pauses a playing animation. A subsequent call to play will continue where it left off.
- play()¶
Same as start()
- replace(key)¶
Selects a different animation to be shown.
- Parameters:
- key - a key in the animations dictionary that specifies which animation to show
- Raises:
- KeyError if the key to use to replace an animation is not found in the dictionary
- setCenteredLoc(loc)¶
- Sets a new location for this widget. loc is a tuple of X and Y values (X, Y)
But it sets the center of the image of this widget to the X,Y position It also changes the rect of the widget
- Parameter:
- loc - a tuple of X,Y coordinates
- setLoc(locTuple)¶
- 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
- Parameter:
- loc - a tuple of X,Y coordinates
- setLoop(trueOrFalse)¶
Sets a value telling the animation if it should loop or not.
- Parameter:
- 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 start will play 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.
This method typically returns False, but will return True when an animation ends (and it is not looping)
TextCheckBox¶
- class pygwidgets.TextCheckBox(window, loc, text, value=True, fontName=None, fontSize=20, 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:
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.
In your event 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
At the bottom of your big loop, draw the checkBox:
myCheckBox.draw()
- Parameters:
- window - the window to draw the checkbox inloc - a tuple specifying the upper left corner to draw the checkbox on the surfacetext - the text for the label that appears next to the checkbox
- Optional keyword parameters:
- value - True for on, False for off (default is True)fontName - font to use for text, or font file, or None for system font (default is None)fontSize - size of the font to use (defaults to 20)size - used for both the width and the height (assuming a square box) - (default is 16 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 event loop (inside 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 timeTrue when the user has toggled the checkbox.
- hide()¶
Make this widget invisible.
- moveX(nPixels)¶
Move some number of pixels in the X direction
- Parameter:
- nPixels - the number of pixels to move
- moveXY(nPixelsX, nPixelsY)¶
Move some number of pixels in the X and Y directions
- Parameters:
- nPixelsX - the number of pixels to move in the X directionnPixelsY - the number of pixels to move in the Y direction
- moveY(nPixels)¶
Move some number of pixels in the Y direction
- Parameter:
- nPixels - the number of pixels to move
- overlapsObject(oOther)¶
Checks for overlap of two pygwidgets objects
- Parameter:
- oOther - a second object to compare to
- Returns:
- True or False if the rect of this object overlaps with the rect of another pygwidgets object
- setCenteredLoc(loc)¶
- Sets a new location for this widget. loc is a tuple of X and Y values (X, Y)
But it sets the center of the image of this widget to the X,Y position It also changes the rect of the widget
- Parameter:
- loc - a tuple of X,Y coordinates
- 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
- Parameter:
- loc - a tuple of X,Y coordinates
- setValue(trueOrFalse)¶
Sets a new value for the checkBox to the value passed in.
- show()¶
Make this widget visible.
- toggleValue()¶
Switches the current value of a checkBox and returns the new value
Functions:¶
buildPathFromRelativePath¶
- pygwidgets.buildPathFromRelativePath(relativePath)¶
This function is needed because of the way that PyInstaller works. PyInstaller creates a temp folder and stores the path in _MEIPASS. When running as an executable, it builds a path to this temporary folder. When running in development, it just builds the full absolute path from the relative path.
- Parameter:
- relativePath - relative path to the image file
- Returns:
- an absolute path that can be used during development or from an executable file
getPygwidgetsVersion¶
- pygwidgets.getPygwidgetsVersion()¶
Called to retrieve the current version of pygwidgets
- Returns:
- the current major version of pygwidgets
loadImage¶
- pygwidgets.loadImage(relativePath)¶
Resolves a path to an image file and loads it. This is typically used to load an image so you can then get its rect - with a call to theImage.get_rect(), then extract the width and height
- Parameter:
- relativePath - relative path to the image file
- Returns:
- an image