如何在 Python 中创建曲折运动?
Posted
技术标签:
【中文标题】如何在 Python 中创建曲折运动?【英文标题】:How to create zigzag movements in Python? 【发布时间】:2014-06-18 10:15:15 【问题描述】: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】:创建新变量
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
【讨论】:
以上是关于如何在 Python 中创建曲折运动?的主要内容,如果未能解决你的问题,请参考以下文章