我正在尝试在Tkinter中使用键盘驱动的事件,以便我可以在画布小部件周围移动一个对象。向上,向下,向左和向右工作正常但是当我尝试将两个键编程在一起时,运动不是平滑的对角线运动。此外,每当一个键被击中时,物体就会移动,然后会有轻微的延迟,然后它会平稳地移动。 如何实现平滑运动按下按键,如何实现平滑的对角运动?
这是到目前为止的代码:
from tkinter import *
x = 10
y = 10
a = 100
b = 100
def change_coord(event):
if event.keysym == 'Up':
canvas1.move(rect, 0,-5)
if event.keysym == 'Up' and 'Right':
canvas1.move(rect, 5,-5)
if event.keysym == 'Up' and 'Left':
canvas1.move(rect, -5,-5)
if event.keysym == 'Down':
canvas1.move(rect, 0,5)
if event.keysym == 'Down' and 'Right':
canvas1.move(rect, 5,5)
if event.keysym == 'Down' and 'Left':
canvas1.move(rect, -5,5)
if event.keysym == 'Right':
canvas1.move(rect, 5,0)
if event.keysym == 'Left':
canvas1.move(rect, -5,0)
window = Tk()
window.geometry("400x200")
#canvas and drawing
canvas1=Canvas(window, height = 200, width = 400)
canvas1.grid(row=0, column=0, sticky=W)
coord = [x, y, a, b]
rect = canvas1.create_rectangle(*coord, outline="#fb0", fill="#fb0")
#capturing keyboard inputs and assigning to function
window.bind_all('<Up>', change_coord)
window.bind_all('<Down>', change_coord)
window.bind_all('<Left>', change_coord)
window.bind_all('<Right>', change_coord)
window.mainloop()
非常感谢!
修改
感谢您的所有建议。我一直试图实现一个动画循环来解决箭头键后的轻微延迟,但现在卡住了。我的新代码如下所示,但运行程序不会导致画布项目移动。首先,是动画循环正确的想法,其次我在哪里调用'移动'功能来让项目移动。请帮忙 - 谢谢!
from tkinter import *
x = 10
y = 10
a = 100
b = 100
direction = None
def move():
global x_vel
global y_vel
global direction
if direction is not None:
canvas1.move(rect, x_vel,y_vel)
after(33,move)
def on_keypress(event):
global direction
global x_vel
global y_vel
if event.keysym == "Left":
direction == "left"
x_vel = -5
y_vel = 0
if event.keysym == "Right":
direction == "right"
x_vel = 5
y_vel = 0
if event.keysym == "Down":
direction == "down"
x_vel = 0
y_vel = 5
if event.keysym == "Up":
direction == "up"
x_vel = 0
y_vel = -5
def on_keyrelease(event):
global direction
direction = None
window = Tk()
window.geometry("400x200")
#canvas and drawing
canvas1=Canvas(window, height = 200, width = 400)
canvas1.grid(row=0, column=0, sticky=W)
coord = [x, y, a, b]
rect = canvas1.create_rectangle(*coord, outline="#fb0", fill="#fb0")
#capturing keyboard inputs and assigning to function
window.bind_all('<KeyPress>', on_keypress)
window.bind_all('<KeyRelease>', on_keyrelease)
window.mainloop()
答案 0 :(得分:2)
绑定到基本键是错误的方法。相反,绑定到按键和按键释放,并使用它来创建按键的字典。每N ms运行一个使用该字典确定如何移动对象的函数。 (我不确定Tkinter计时器是否具有正确执行此操作所需的质量。)
如果程序失去焦点,请务必清除字典。