简体   繁体   English

Python tkinter 画布动画

[英]Python tkinter canvas animation

so i was writing this code and when i run it my animated ball is going only right side but not turning back can you help me所以我正在编写这段代码,当我运行它时,我的动画球只向右侧走,但不会回头,你能帮帮我吗

import tkinter
canvas = tkinter.Canvas(bg="white",width=(900),height=(900))
canvas.pack()


def ball():
    global x
    canvas.delete("all")
    canvas.create_oval(x-100,y-100,x+100,y+100,fill="orange",outline="black",width=4)
    x = x+5
    if x <800:
        canvas.after(20,ball)

def ball_back():
    global x
    canvas.delete("all")
    canvas.create_oval(x-100,y-100,x+100,y+100,fill="orange",outline="black",width=4)
    x = x-5
    if x >100:
        canvas.after(20,ball_back)

x = 100
y = 300
ball()
ball_back()

The way Tkinter calls those methods is a little different than what you may expect. Tkinter 调用这些方法的方式与您的预期略有不同。 Both ball and ball_back are being called right away one after another. ballball_back都被一个接一个地立即调用。 Since ball_back fails the if statement right out of the gate (x is greater than 100) it never gets called again.由于ball_back使if语句失败(x 大于 100),因此它永远不会再次被调用。 Try changing the last lines of ball to this:尝试将ball的最后几行更改为:

x = x+5
if x <800:
    canvas.after(20,ball)
else:
    canvas.after(20, ball_back)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM