您绝对不应在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()