更新变量时代码不起作用

时间:2016-08-01 13:22:18

标签: python list python-2.7

我试图在一个简单的GUI中显示两张卡片图片(只能在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()

问题是,当我更新img_center [0]的值时,代码将不会显示第二个图像“ ace-hearts ”。

然后我删除了

img_center[0] += IMG_WIDTH

第二张图片正确显示在“两个黑桃”的“顶部”。

有谁知道为什么更新此变量不会产生正确的结果( ace-hearts 应显示在双心的右侧)?

1 个答案:

答案 0 :(得分:1)

draw_image的第二和第四个参数是center_sourcecenter_dest。绘制第二张图片时,您需要保持center_source相同,并且只修改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))

工作示例:http://www.codeskulptor.org/#user41_5Cm7ZlARnQ_0.py