0

好,朋友们。当我单击生成按钮时,我试图在 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()
4

1 回答 1

1

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

def display(self):
    self.canvas.delete("circle")
    for i in range(0, 10):
        ...
于 2014-12-27T16:12:08.403 回答