CSC111 Resizing Graphic Objects
--D. Thiebaut (talk) 11:15, 20 April 2014 (EDT)
Note: Depending on the installation of your Python and Tkinter program (that Python uses to perform graphics), the code below may or may not work. On some installation of Tkinter, the code shows animation and objects being resized, on some other computers the resizing of items does not show up.
This example uses the graphics library available on this page.
The resize method of the Car class performs the resizing in three steps:
- First all the components of the car are removed. This effectively removes them from the canvas, and forces the canvas to "forgets" them.
- It then calls the __init__() constructor to create a brand new collection of components (body, top, wheels).
- It draws the new collection on the canvas
# Demo program for resizing a graphic object.
# Highlighted code illustrates the resize method of the Car class.
# D. Thiebaut
#
from graphics111 import *
from random import seed
from random import randrange
from time import sleep
MAXWIDTH = 800
MAXHEIGHT = 600
class Car:
def __init__( self, x, y, width, height, color ):
self._x = x
self._y = y
self._width = width
self._height = height
self._color = color # list of 3 ints between 0 and 255
# build the body
self._top = Rectangle( x+width//4, y-height//2,
width//2, height//2,
color )
self._body = Rectangle( x, y, width, height, color )
# build the wheels
self._w1 = Wheel( x + width//4, y + height, width//5 )
self._w2 = Wheel( x + 3*width//4, y + height, width//5 )
self._valid = False
def setRandomColor( self ):
self._top.setRandomColor()
self._body.setRandomColor()
def getTotalHeight( self ):
return self._height*2 + self._width//10
def getTotalWidth( self ):
return self._width
def draw( self, canvas ):
self._canvas = canvas
self._body.draw( canvas )
self._top.draw( canvas )
self._w1.draw( canvas )
self._w2.draw( canvas )
def move( self, canvas, dx, dy ):
self._body.move( canvas, dx, dy )
self._top.move( canvas, dx, dy )
self._w1.move( canvas, dx, dy )
self._w2.move( canvas, dx, dy )
self._x = int( self._x + dx )
self._y = int( self._y + dy )
def resize( self, canvas, scaleFactor ):
self._body.remove( canvas )
self._top.remove( canvas )
self._w1.remove( canvas )
self._w2.remove( canvas )
self.__init__( self._x, self._y,
int( self._width * scaleFactor ),
int( self._height * scaleFactor ),
self._color )
self.draw( canvas )
# ========================================================
# Main Program
# ========================================================
def main():
# open the window and get access to its canvas
win = GraphicsWindow(MAXWIDTH, MAXHEIGHT)
canvas = win.canvas()
# draw something
p1 = Polygon( (100, 100, 150, 50, 350, 50, 400, 100), (255, 0, 0 ) )
p1.draw( canvas )
car1 = Car( 150, 75, 100, 20, (250, 250, 0 ) )
car1.draw( canvas )
scaleFactor = 1.05
for i in range( 0, 40 ):
car1.resize( canvas, scaleFactor )
# wait and respond to events
win.wait()
win.close()
main()