在tkinter画布中生成10个球

时间:2014-12-27 15:59:09

标签: python-3.x canvas tkinter drawing tkinter-canvas

好的伙计们。 当我点击生成按钮时,我试图在Tkinter画布中生成10个随机颜色的球。 程序有效,随机颜色选择适用于球,但我一次只生成一个球。 每当我点击按钮时,它随机移动球,但我想要的是每次10个随机位置的10个球。我在Linux机器上使用Python 3.4。 这是我得到的代码:

from tkinter import *
import random # to generate random balls

colors = ["red", "blue", "purple", "green", "violet", "black"]

class RandomBalls:
    """
    Boilerplate code for window in Tkinter
    window = Tk()
    window.title("Random title")
    window.mainloop()
    """


    def __init__(self):
        """
        Initialize the window and add two frames, one with button, and another one with
        canvas
        :return:
        """

        window = Tk()
        window.title("Random balls")

        # A canvas frame
        frame1 = Frame(window)
        frame1.pack()
        self.canvas = Canvas(frame1, width = 200, height = 300, bg = "white")
        self.canvas.pack()


        # A button frame
        frame2 = Frame(window)
        frame2.pack()
        displayBtn = Button(frame2, text = "Display", command = self.display)
        displayBtn.pack()

        window.mainloop()

    def display(self):
        for i in range(0, 10):
            self.canvas.delete("circle")  # delete references to the old circle
            self.x1 = random.randrange(150)
            self.y1 = random.randrange(200)
            self.x2 = self.x1 + 5
            self.y2 = self.y1 + 5
            self.coords = self.x1, self.y1, self.x2, self.y2
            self.canvas.create_oval(self.coords, fill = random.choice(colors), tags = "circle")
        self.canvas.update()


RandomBalls()

1 个答案:

答案 0 :(得分:1)

每次循环都会删除之前创建的所有内容,包括您在上一次迭代中创建的内容。将delete语句移到循环之外:

def display(self):
    self.canvas.delete("circle")
    for i in range(0, 10):
        ...