gpt4 book ai didi

python - 如何在 Tkinter 中实现 Canvas 项目的平滑移动?

转载 作者:行者123 更新时间:2023-12-01 05:01:16 26 4
gpt4 key购买 nike

我正在尝试在 Tkinter 中使用键盘驱动的事件,以便我可以在 Canvas 小部件周围移动对象。上、下、左、右工作正常,但当我尝试将两个键一起编程时,运动不是平滑的对角运动。此外,每当按下一个键时,物体就会移动,然后有轻微的延迟,然后就平滑地移动。如何在按下按键的那一刻实现平滑的运动以及如何实现平滑的对角运动?

这是到目前为止的代码:

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()

非常感谢!

编辑:

感谢您的所有建议。我一直在尝试实现一个动画循环来解决按下箭头键后的轻微延迟,但现在被卡住了。我的新代码如下所示,但运行该程序不会导致 Canvas 项目移动。首先,动画循环的想法是否正确,其次,我在哪里调用“移动”函数来让项目移动。请帮忙 - 谢谢!

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()

最佳答案

绑定(bind)到基本键是错误的方法。相反,绑定(bind)到按键按下和按键释放,并使用它来创建按下的按键的字典。每 N 毫秒运行一个函数,使用该字典来确定如何移动对象。 (我不确定 Tkinter 计时器是否具有正确执行此操作所需的质量。)

如果程序失去焦点,请务必清除字典。

关于python - 如何在 Tkinter 中实现 Canvas 项目的平滑移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26126792/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com