如何在Python中创建锯齿形运动?

时间:2014-06-18 10:15:15

标签: python tkinter zigzag

from tkinter import *

def move():
    global x1, y1, dx, dy, flag, n, z

    x1, y1 = x1 + dx, y1 + dy

    if x1 > 360: 
        x1, dx, dy = 360, -15, 5
        can1.itemconfig(oval1, fill = "purple")

    if x1 < 10:
        x1, dx, dy = 10, 15, 5
        can1.itemconfig(oval1, fill = "red")

    if y1 == 360:
        x1, dx, dy = 360, -15, -5
        can1.itemconfig(oval1, fill = "green")


    can1.coords(oval1, x1, y1, x1 + 30, y1 + 30)

    if flag > 0:
        abl1.after(50, move)

def stop():
    global flag
    flag = 0

def start():
    global flag
    if flag == 0:
        flag = 1
        move()

###

x1, y1 = 10, 10
dx, dy = 15, 5
n = 0


flag = 0

###

abl1 = Tk()
abl1.title("Animációs gyakorlat Tkinter-rel")

can1 = Canvas(abl1, bg = "dark grey", height = 400, width = 400)
can1.pack(side=LEFT)

oval1 = can1.create_oval(x1, y1, x1 + 30, y1 + 30, fill = "white")

but1 = Button(abl1, text = "Quit", command = abl1.destroy).pack(side=BOTTOM, padx = 3, pady = 5)
but2 = Button(abl1, text = "Start", command = start).pack(padx = 3, pady = 5)
but3 = Button(abl1, text = "Stop", command = stop).pack(padx = 3, pady = 5)

abl1.mainloop()

使用此代码,球会以锯齿形移动自动移动到底部,但是当它到达底部时,它应该返回到顶部然后再次返回到底部。我尝试了几次,但我无法解决。

1 个答案:

答案 0 :(得分:1)

创建新变量

is_moving_down = True

新功能向上移动然后

if is_moving_down:
    move_down()
else:
    move_up()

现在你需要改变方向

if some_conditions:
    is_moving_down = True
else:
    is_moving_down = False