如何使用Arrow键在Tkinter画布中移动图像?
Tkinter Canvas小部件是Tkinter库中最通用的小部件之一。它用于创建各种形状、图像和动画对象。我们可以使用 move() 方法为在Canvas小部件中定义的图像提供动态属性。
通过在 move(Image,x,y) 方法中将图像和坐标定义为参数,可以在Canvas中移动Image。我们需要在全局声明图像,以便跟踪Canvas中的Image位置。
我们可以按照以下步骤使我们的图像在画布中可移动,
- 首先,定义Canvas小部件并将图像添加到其中。
-
定义 move() 函数,允许在Canvas中图像可动态移动。
-
将箭头键与允许在Canvas中移动图像的函数绑定。
示例
#导入所需库
from tkinter import *
from PIL import Image, ImageTk
#创建一个tkinter帧的实例
win=Tk()
#设置tkinter窗口的大小
win.geometry('700x350')
#定义一个Canvas小部件
canvas=Canvas(win,width=600,height=400,bg='white')
canvas.pack(pady=20)
#添加图像到Canvas小部件
image=ImageTk.PhotoImage(Image.open('favicon.ico'))
img=canvas.create_image(250,120,anchor=NW,image=image)
def left(e):
x=-20
y=0
canvas.move(img,x,y)
def right(e):
x=20
y=0
canvas.move(img,x,y)
def up(e):
x=0
y=-20
canvas.move(img,x,y)
def down(e):
x=0
y=20
canvas.move(img,x,y)
#绑定move函数
win.bind('',left)
win.bind('',right)
win.bind('',up)
win.bind('',down)
win.mainloop()
输出
运行以上代码将显示一个窗口,其中包含一个可以使用箭头键在窗口中移动的图像。
您可以使用箭头键在画布上移动对象。