gpt4 book ai didi

python - 为什么我的 tkinter 椭圆形速度固定但仍会加速?

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

我正在尝试使用 tkinter 使这个椭圆在 Canvas 上流畅地移动,但尽管速度固定,但我移动得越多,它似乎就会加速。即使在调试时,我也注意到我的速度变量不会增加到超过所需值。我无法确定是什么导致了这种加速,有人可以指出发生了什么吗?

这是我的代码:

from tkinter import*

window = Tk()
canvas = Canvas(window, width = 300, height = 300, bg ='white')
canvas.focus_set()

speedx = 0
speedy = 0
speed = 1

x1=40
y1=40

oval=canvas.create_oval(x1-10,y1-10,x1+10,y1+10,width=2,fill='orange')

def key_press(event):
global x1, y1
global speedx, speedy, speed

button = event.keysym
if button == 'Up':
speedx = 0
speedy = -speed
elif button == 'Down':
speedx = 0
speedy = speed
elif button == 'Right':
speedx = speed
speedy = 0
elif button == 'Left':
speedx = -speed
speedy = 0
move()

def move():
global x1,y1
global oval
global speedx, speedy
x1 += speedx
y1 += speedy
canvas.delete(oval)
oval = canvas.create_oval(x1+10,y1-10,x1-10,y1+10,width=2,fill='orange')
window.after(10, move)

def key_release(event):
global speedx, speedy
speedx = 0
speedy = 0


canvas.bind('<KeyPress>', key_press)
canvas.bind("<KeyRelease>", key_release)
canvas.pack(padx =5, pady =5)
window.mainloop()

最佳答案

问题是你调用window.after(10, move)从你的move内部功能而无需再次取消。这会生成一个永无休止的循环调用 move对于每个 <KeyPress>事件。

你可以做的就是保存 after调用一个变量。这样您就可以确保move不会从此循环外部再次调用,另外您可以使用它来取消 after调用按键释放:

from tkinter import *

window = Tk()
canvas = Canvas(window, width = 300, height = 300, bg ='white')
canvas.focus_set()

speedx = 0
speedy = 0
speed = 1

# Make variable to store after call object
after_obj = None

x1=40
y1=40

oval=canvas.create_oval(x1-10,y1-10,x1+10,y1+10,width=2,fill='orange')

def key_press(event):
global x1, y1
global speedx, speedy, speed
global after_obj
button = event.keysym
if button == 'Up':
speedx = 0
speedy = -speed
elif button == 'Down':
speedx = 0
speedy = speed
elif button == 'Right':
speedx = speed
speedy = 0
elif button == 'Left':
speedx = -speed
speedy = 0
# Only call move from here if there is no after scheduled
if after_obj is None:
move()

def move():
global x1,y1
global oval
global speedx, speedy
global after_obj
x1 += speedx
y1 += speedy
canvas.delete(oval)
oval = canvas.create_oval(x1+10,y1-10,x1-10,y1+10,width=2,fill='orange')
# Save the after call object
after_obj = window.after(10, move)

def key_release(event):
global speedx, speedy
global after_obj
# When pressing multiple buttons at the same time you can get a key release without an after_obj, so check if it exists then cancel it
if after_obj:
window.after_cancel(after_obj)
# Reset after_obj to None so move can be called from key_press again
after_obj = None
speedx = 0
speedy = 0


canvas.bind('<KeyPress>', key_press)
canvas.bind("<KeyRelease>", key_release)
canvas.pack(padx =5, pady =5)
window.mainloop()

关于python - 为什么我的 tkinter 椭圆形速度固定但仍会加速?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49755973/

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