Ekaterina1234 Ekaterina1234 - 4 months ago 9
Python Question

The code does not work when I update a variable

I'm trying to display two images of cards in a simple GUI(can only be accessed online at http://www.codeskulptor.org/#user41_8Poew9PXI8_1.py)

import simplegui

#images to be displayed
ace_hearts = simplegui.load_image("http://i.imgur.com/Nbr6Dzi.png")
two_spades = simplegui.load_image("http://i.imgur.com/OWayJ1T.png")

# global constants
WIDTH = 800
HEIGHT = 100


# mouseclick handler
def click(pos):
return pos


# draw handler
def draw(canvas):
IMG_WIDTH = 67
IMG_HEIGHT = 100
img_center = [IMG_WIDTH // 2, IMG_HEIGHT // 2]
canvas.draw_image(two_spades, (img_center),
(IMG_WIDTH, IMG_HEIGHT), (img_center), (IMG_WIDTH, IMG_HEIGHT))
img_center[0] += IMG_WIDTH
canvas.draw_image(ace_hearts, (img_center),
(IMG_WIDTH, IMG_HEIGHT), (img_center), (IMG_WIDTH, IMG_HEIGHT))

# create frame and register draw handler
frame = simplegui.create_frame("Test image", WIDTH, HEIGHT)
frame.set_canvas_background("Gray")
frame.set_mouseclick_handler(click)
frame.set_draw_handler(draw)

# start frame
frame.start()


The problem is, that when I update the value of img_center[0], the code won't display the second image "ace-hearts".

Then I remove the line

img_center[0] += IMG_WIDTH


The second image is correctly displayed "on top" of "two-spades".

Does anyone know why updating this variable won't produce the correct results (ace-hearts should be displayed to the right of two-hearts)?

Answer

Second and fourth parameter given to draw_image are center_source and center_dest. When you draw the second image you need to keep center_source the same and only modify center_dest:

def draw(canvas):
    IMG_WIDTH = 67
    IMG_HEIGHT = 100
    source_center = [IMG_WIDTH // 2, IMG_HEIGHT // 2]
    dest_center = [IMG_WIDTH // 2, IMG_HEIGHT // 2]
    canvas.draw_image(two_spades, (source_center), 
        (IMG_WIDTH, IMG_HEIGHT), (dest_center), (IMG_WIDTH, IMG_HEIGHT))
    dest_center[0] += IMG_WIDTH
    canvas.draw_image(ace_hearts, (source_center), 
        (IMG_WIDTH, IMG_HEIGHT), (dest_center), (IMG_WIDTH, IMG_HEIGHT))

Working example: http://www.codeskulptor.org/#user41_5Cm7ZlARnQ_0.py