【发布时间】:2018-09-02 12:21:05
【问题描述】:
我想将我的程序弹跳球程序翻译成 OOP,以便稍微训练 OOP。
我遇到的问题是,如果我在包含无限循环的对象的一个实例上调用一个函数,下一个实例将永远不会调用它的函数。导致只有一个球在移动。
import tkinter as tk
import time
import random
#Define root windows
root = tk.Tk()
root.geometry("800x800")
root.title("TkInter Animation Test")
#Define canvas that is inside the root window
canvas_width = 700
canvas_height = 700
canvas = tk.Canvas(root, width= canvas_width, height= canvas_height, bg="Black")
canvas.pack()
class Oval():
#Oval creation inside the canvas
def __init__(self, y1, x1, y2, x2, color):
self.y1 = y1
self.x1 = x1
self.y2= y2
self.x2= x2
self.oval = canvas.create_oval(self.x1, self.y1, self.x2, self.y2, fill=color)
#Moving the Oval(ov1)
def move(self):
self.xd = random.randint(5,10)
self.yd = random.randint(5,10)
while True:
canvas.move(self.oval, self.xd, self.yd)
# print(self.yd, self.xd)
self.coords = canvas.coords(self.oval)
# print (self.coords)
if self.coords[3] + self.yd >= 700 or self.coords[1] + self.yd <= 0:
if self.yd < 0:
self.yd = random.randint(5,10)
else:
self.yd = -(random.randint(5,10))
if self.coords[2] + self.xd >= 700 or self.coords[0] + self.xd <= 0:
if self.xd < 0:
self.xd = random.randint(5,10)
else:
self.xd = -(random.randint(5,10))
root.update()
time.sleep(.01)
ov1 = Oval(10,10,40,40, "blue")
ov2 = Oval(80,80,120,120, "red")
ov3 = Oval(240,240,270,270, "Yellow")
ov4 = Oval(360,360,400,400, "Green")
ov5 = Oval(500,500,540,540, "white")
#Problem is that ov1.move() has a internal loop and ov2.move() will never be called
# ov1.move()
# ov2.move()
# ov3.move()
# ov4.move()
# ov5.move()
tk.mainloop()
【问题讨论】:
-
当第一个椭圆在
True循环中移动时。它永远不会继续 -
是的,我确实意识到了这一点。但我不知道如何解决这个问题。
-
你可以单独制作椭圆(没有类),然后它们在一个循环中移动
-
对不起,我不想太饱了 :) 但我已经完成了。但我想尝试使用 oop 来实现使用 oop 的常规
标签: python loops oop animation tkinter