我创建了一些代码来显示两个球的移动,但是当我运行它时,它不会显示球的移动球。而且它停止运行并忽略无限循环这是我到目前为止的代码:
import tkinter as tk
class ObjectHolder:
def __init__(self, pos, velocity, radius, id):
self.id = id # the id of the canvas shape
self.pos = pos # the position of the object
self.r = radius # the radius of incluence of the object
self.velocity = velocity # the velocity of the object
def moveobject(object):
x = object.pos[0] + object.velocity[0] # moves the object where
y = object.pos[1] + object.velocity[1] # 0=x and 1=y
object.pos = (x, y)
canvas.move(object, x, y)
class App():
def __init__(self, canvas):
self.canvas = canvas
self.objects = []
for i in range(0, 2):
position = ((i+1)*100, (i+1)*100)
velocity = (-(i+1)*10, -(i+1)*10)
radius = (i + 1) * 20
x1 = position[0]-radius
y1 = position[1]-radius
x2 = position[0]+radius
y2 = position[1]+radius
id = canvas.create_oval(x1, y1, x2, y2)
self.objects.append(ObjectHolder(position, velocity, radius, id))
self.symulation(self.objects)
def symulation(self, objects):
for object in objects: # this moves each object
ObjectHolder.moveobject(object)
# This part doesn't work. It is supposed to update the canvas
# and repeat forever.
self.canvas.update()
root.update()
self.canvas.after(50, self.symulation, objects)
root = tk.Tk()
canvas = tk.Canvas(root, width=800, height=600, bg="light blue")
canvas.pack()
App(canvas)
你的代码有很多问题。其中一个大问题是更新现有画布对象位置的方式。
move()
方法需要知道移动量(x和y值的变化),而不是新的绝对位置。你知道吗当我修正时,结果是速度太大了,所以我把它们减少到只有你值的10%。你知道吗
另一个问题是
ObjectHolder
类的实现方式。首先,moveobject()
方法没有self
参数,它应该使用这个参数而不是object
参数。您可能还应该简单地将方法重命名为move()
。你知道吗下面的代码运行并设置运动的动画。你知道吗
相关问题 更多 >
编程相关推荐