如何使用tkinter after()一次创建一个矩形?

时间:2019-08-06 21:56:07

标签: python tkinter

我有一个采用2d数组的程序。数组内部是“ GREEN”或“ BLACK”值。黑色或绿色取决于密度变量,该密度变量可通过屏幕上的文本框进行编辑。我创建一个画布,然后为数组的每个索引创建一个1x1矩形,将其着色为黑色或绿色。之后,我想做的就是遍历数组,并将绿色矩形设置为红色。另外,如果北,东,南和西的任何矩形都是绿色,我也想将它们设置为红色。这就是我的问题所在。我想在最后一步中一次完成一个矩形,并更新屏幕,以便我可以慢慢看到矩形从绿色变为红色。如何逐步而不是一次完成?我试过在几个地方使用after()方法,但还没有改变它的程序行为。如果您有任何想法请告诉我。我最近的尝试是这样:

root.after(5)

第61行。这是我的完整代码:

import tkinter as tk
import random

# 150 x 150 array, initialized all cells to 0-1
a, b = 150, 150;
density = .5

def RedOrGreen():
  c = random.uniform(0,1)
  if c > density:
    d = "GREEN"
  else:
    d = "BLACK"
  return d

class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.density_label = tk.Label(text = "Tree Density")
        self.density_label.pack(side="top")
        self.density_textbox = tk.Entry(bd = 5)
        self.density_textbox.pack(side = "top")
        self.setup = tk.Button(bottomframe, text = "Setup", command = self.setupClick)
        self.setup.pack(side="bottom")
        self.forest = tk.Canvas(self, width = 500, height = 500)

    def setupClick(self):
        print(self.density_textbox.get())
        global density
        density = float(self.density_textbox.get())
        Matrix = [[RedOrGreen() for x in range(a)] for y in range(b)]
        for x in range(a):
            for y in range(b):
                self.forest.create_rectangle(x,y,x+1,y+1, fill = Matrix[x][y], width = 0)
        self.forest.pack()
        for x in range(a):
            for y in range(b):
                if x != 0 and x != 149 and y != 0 and y != 149:
                  if Matrix[x][y] == "GREEN":
                    Matrix[x][y] = "RED"
                    #north
                    if Matrix[x][y-1] == "GREEN":
                        Matrix[x][y-1] = "RED"
                    #east
                    if Matrix[x+1][y] == "GREEN":
                        Matrix[x+1][y] = "RED"
                    #south
                    if Matrix[x][y+1] == "GREEN":
                        Matrix[x][y+1] = "RED"
                    #west
                    if Matrix[x-1][y] == "GREEN":
                        Matrix[x-1][y] = "RED"
        for y in range(b):
            for x in range(a):
                self.forest.create_rectangle(x,y,x+1,y+1, fill = Matrix[x][y], width = 0)
                #root.after(5)

root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
bottomframe = tk.Frame(root)
bottomframe.pack(side = "bottom")
app = Application(master=root)
app.mainloop()

0 个答案:

没有答案