这是一个非常基本的程序,我想用它制作两个移动的球,但实际上只有一个在移动。
我也尝试了一些变体,但无法让第二个球移动;另一个相关问题 - 有些人使用 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()
最佳答案
您永远不应该在 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()
关于python - 在 Tkinter Canvas 中移动球,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25430786/