如何让我的动画循环工作?

时间:2014-10-01 12:19:13

标签: python python-3.x tkinter

我一直在尝试实现一个动画循环,以解决在按箭头键后移动画布项目时遇到的轻微延迟,但现在卡住了。我的代码如下所示,我认为这样可以在按下某个键时启用循环,并在按键被解除时循环停止,但运行该程序不会导致画布项移动。首先,是动画循环的想法是正确的吗?其次,我/我应该在哪里调用“移动”功能来使项目移动?请帮忙 - 谢谢!

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

2 个答案:

答案 0 :(得分:3)

  1. move永远不会被召唤。
  2. 应使用after调用
  3. widget

    def move():
        global x_vel
        global y_vel
        global direction
        if direction is not None:
            canvas1.move(rect, x_vel,y_vel)
        window.after(33,move)  # Indetation.
    
  4. 分配到direction==的错字应为=

    direction = "left"
    

答案 1 :(得分:1)

这样的重复代码
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

通常可以更紧凑地编写。在模块范围,定义一个字典。

dir_vel = {
    'Left': ('left', -5 0),
    'Right': ('right', 5, 0),
    'Down': ('down', 0, 5),
    'Up': ('up', 0, -5),
}

然后在on_keypress中,用

替换上面的替换
    direction, x_vel, y_vel = dir_vel[event.keysym]