在Tkinter帆布移动球

dlo*_*hse 6 python animation tkinter

这是一个非常基本的程序,我想制作两个移动球,但其中只有一个实际移动.

我也尝试了一些变化但是不能让第二个球移动; 另一个相关的问题 - 有些人使用这种move(object)方法来实现这个目标,而其他人则做一个delete(object)然后重新绘制它.我应该使用哪一个?为什么?

这是我的代码,它只是动画/移动一个球:

from Tkinter import *

class Ball:
    def __init__(self, canvas, x1, y1, x2, y2):
    self.x1 = x1
    self.y1 = y1
    self.x2 = x2
    self.y2 = y2
    self.canvas = canvas
    self.ball = canvas.create_oval(self.x1, self.y1, self.x2, self.y2, fill="red")

    def move_ball(self):
        while True:
            self.canvas.move(self.ball, 2, 1)
            self.canvas.after(20)
            self.canvas.update()

# initialize root Window and canvas
root = Tk()
root.title("Balls")
root.resizable(False,False)
canvas = Canvas(root, width = 300, height = 300)
canvas.pack()

# create two ball objects and animate them
ball1 = Ball(canvas, 10, 10, 30, 30)
ball2 = Ball(canvas, 60, 60, 80, 80)

ball1.move_ball()
ball2.move_ball()

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

Bry*_*ley 12

你永远不应该在GUI程序中放置一个无限循环 - 已经有一个无限循环运行.如果你想让你的球独立移动,只需取出循环并让move_ball方法在事件循环上对它自己进行新的调用.这样,你的球将继续永远移动(这意味着你应该在那里进行某种检查以防止这种情况发生)

我通过删除无限循环,稍微调整动画的速度,以及使用随机值移动方向来略微修改程序.所有这些变化都在move_ball方法内部.

from Tkinter import *
from random import randint

class Ball:
    def __init__(self, canvas, x1, y1, x2, y2):
        self.x1 = x1
        self.y1 = y1
        self.x2 = x2
        self.y2 = y2
        self.canvas = canvas
        self.ball = canvas.create_oval(self.x1, self.y1, self.x2, self.y2, fill="red")

    def move_ball(self):
        deltax = randint(0,5)
        deltay = randint(0,5)
        self.canvas.move(self.ball, deltax, deltay)
        self.canvas.after(50, self.move_ball)

# initialize root Window and canvas
root = Tk()
root.title("Balls")
root.resizable(False,False)
canvas = Canvas(root, width = 300, height = 300)
canvas.pack()

# create two ball objects and animate them
ball1 = Ball(canvas, 10, 10, 30, 30)
ball2 = Ball(canvas, 60, 60, 80, 80)

ball1.move_ball()
ball2.move_ball()

root.mainloop()
Run Code Online (Sandbox Code Playgroud)


Cor*_*mer 3

这个函数似乎是罪魁祸首

def move_ball(self):
    while True:
        self.canvas.move(self.ball, 2, 1)
        self.canvas.after(20)
        self.canvas.update()
Run Code Online (Sandbox Code Playgroud)

当你调用它时,你故意让自己陷入无限循环。

ball1.move_ball()    # gets called, enters infinite loop
ball2.move_ball()    # never gets called, because code is stuck one line above
Run Code Online (Sandbox Code Playgroud)