在Tkinter画布中生成多个移动对象

时间:2018-04-07 17:29:03

标签: python user-interface animation canvas tkinter

我一直在使用Tkinter制作一些简单的动画。

我已经编写了一个单个球的代码,可以在一个随机的方向和随机的起始位置围绕屏幕移动并从画布的边缘反弹。

我想为多个球重复此操作,而无需为每个球单独编写代码。我尝试使用语句for n in xrange(5),但它似乎没有效果。我希望能够创建多个球,所有球都是从随机位置开始并随机移动。

这是我的代码:

from Tkinter import *
import random
import time
shop_window = Tk()
shop_window.overrideredirect(1)
shop_window.geometry("254x310")
canvas = Canvas(shop_window, width=254, height=310, bg="snow2", bd=0, highlightthickness=0, relief="ridge")
canvas.pack()
x = random.randint(0, 254)
y = random.randint(0, 310)
ball = canvas.create_oval((x-10, y-10, x+10, y+10), fill="saddle brown")
xspeed = random.randint(1, 5)
yspeed = random.randint(1, 5)
while True:
    canvas.move(ball, xspeed, yspeed)
    pos = canvas.coords(ball)
    if pos[3] >= 310 or pos[1] <= 0:
        yspeed = -yspeed
    if pos[2] >= 254 or pos[0] <= 0:
        xspeed = -xspeed
    Tk.update(shop_window)
    time.sleep(0.025)
    pass

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

这是一个OOP方法,它创建一个import logging import psycopg2 as pg #Code completion works fine here. logger = logging.getLogger() logger.info("Hello World!") #Code completion works fine here. con = pg.connect("dbname='postgres' port='5432'") #Code completion not working! cur = con.cursor() 个对象的集合,在画布上跟踪它们,并在每个回合更新它们。

Ball