0

I am new to Python and was wondering how I could make an image change to another when a key is pressed. I want my image to change from GuyUp.gif to GuyDown.gif when I press the down arrow key so it looks like my guy is actually walking normally. My code in Python looks like this:

from tkinter import *
tk = Tk()
tk.title("Triangle Movement")
tk.resizable(0, 0)
canvas = Canvas(tk, width=500, height=500)
canvas.pack()
tk.update()
guyup = PhotoImage(file = 'GuyUp.gif')
canvas.create_image(5, 5, image = guyup, anchor = NW)
def movetriangle(event):
    if event.keysym == 'Up':
        canvas.move(1, 0, -4)
    elif event.keysym == 'Down':
        canvas.move(1, 0, 4)
    elif event.keysym == 'Left':
        canvas.move(1, -4, 0)
    elif event.keysym == 'Right':
        canvas.move(1, 4, 0)
    elif event.keysym == 'w':
        canvas.move(2, 0, -4)
    elif event.keysym == 's':
        canvas.move(2, 0, 4)
    elif event.keysym == 'a':
        canvas.move(2, -4, 0)
    else:
        canvas.move(2, 4, 0)
canvas.bind_all('<KeyPress-Up>', movetriangle)
canvas.bind_all('<KeyPress-Down>', movetriangle)
canvas.bind_all('<KeyPress-Left>', movetriangle)
canvas.bind_all('<KeyPress-Right>', movetriangle)
canvas.bind_all('<KeyPress-w>', movetriangle)
canvas.bind_all('<KeyPress-s>', movetriangle)
canvas.bind_all('<KeyPress-a>', movetriangle)
canvas.bind_all('<KeyPress-d>', movetriangle)

I do have the two images and would like to put it in my elif statement with the keysym of 'Down' Thank you for your help!

4

1 回答 1

1

首先是评论:您已经以不同的方式绑定了所有按键,那么为什么要在回调中使用所有条件呢?只需定义单独moveup的 ,movedown等函数并将它们绑定到适当的按键。

现在,对于您的图像切换,您需要应用程序中的状态来了解显示哪个图像以及不显示哪个图像。由于您使用的是全局变量并且没有类,因此您还必须将此信息存储在全局变量中。更改代码的以下部分:

current_image = PhotoImage(file='GuyUp.gif')
image_id = canvas.create_image(5, 5, image=current_image, anchor=NW)
other_image = PhotoImage(file='GuyDown.gif')

并添加以下功能

def swap_images():
    global current_image, other_image, image_id
    x, y = canvas.coords(image_id)
    canvas.delete(image_id)
    image_id = canvas.create_image(x, y, image=other_image)
    current_image, other_image = other_image, current_image

您现在可以将此函数放置在程序逻辑中您喜欢的任何位置。

您可能最好将您在类中编写的所有内容打包并使用实例变量而不是全局变量,并将函数适应这种情况留作练习;)


编辑:修复了create_image方法中缺少的关键字。

我也意识到你必须改变你的canvas.move调用来使用image_id而不是1作为标识符。也许比存储它更好的选择是在对象本身上使用标签。

于 2013-04-29T23:28:38.750 回答