如何使用键盘键同时移动两个图像?

问题描述

下面的代码只是游戏的开始,我一次只能移动一张图片。如何更改它,以便我既可以移动箭头键又可以移动WASD键?我只需要水平移动它即可。

from tkinter import *
import threading

root = Tk()
root.title('Plane Wars Blitz')
root.geometry("1200x800")

w = 1200
h = 800
x = w/2
y = h/2

my_canvas = Canvas(root,width = w,height = h,bg = "light blue")
my_canvas.pack(pady=20)

ship1=PhotoImage(file="shipup.png")
ship2=PhotoImage(file="shipdown.png")

ship1image = my_canvas.create_image(600,700,image=ship1)
ship2image = my_canvas.create_image(600,100,image=ship2)

def left1(event):
    x = -20
    y = 0
    my_canvas.move(ship1image,x,y)

def right1(event):
    x = 20
    y = 0
    my_canvas.move(ship1image,y)

def left2(event):
    x = -20
    y = 0
    my_canvas.move(ship2image,y)

def right2(event):
    x = 20
    y = 0
    my_canvas.move(ship2image,y)


root.bind("<Left>",left1)
root.bind("<Right>",right1)
root.bind("<a>",left2)
root.bind("<s>",right2)
    

root.mainloop() 

解决方法

我没有适合您的代码,但是有主意。

  1. 将KeyPress,KeyRelease绑定到所有键,例如
  2. 回调所有绑定以仅记录按下或释放的键以及其他一些必需的状态。
  3. 计时以扫描所有按键的状态来确定运动的方式。