在Tkinter中高效地创建网格

时间:2019-03-17 06:28:48

标签: python tkinter

我目前正在使用以下代码通过tkinter模块在python中创建一个窗口大小的网格

import tkinter as tk

class Frame():

    def __init__(self, *args, **kwargs):
        # Setup Canvas
        self.c = tk.Canvas(root, height=500, width=500, bg='white')
        self.c.pack(fill=tk.BOTH, expand=True)
        self.c.bind('<Configure>', self.createGrid)
        self.pixel_width = 20
        self.pixel_height = 20

        # Setup binds
        self.c.bind("<ButtonPress-1>", self.leftClick)

    def leftClick(self, event):
        items = self.c.find_closest(event.x, event.y)
        if items:
            rect_id = items[0]
            self.c.itemconfigure(rect_id, fill="red")

    def createGrid(self, event=None):
        for x in range(0, self.c.winfo_width()):
            for y in range(0, self.c.winfo_height()):
                x1 = (x * self.pixel_width)
                x2 = (x1 + self.pixel_width)
                y1 = (y * self.pixel_height)
                y2 = (y1 + self.pixel_height)
                self.c.create_rectangle(x1,y1,x2,y2)
        self.c.update()

root = tk.Tk()
gui = Frame(root)
root.mainloop()

如果将画布的高度和宽度设置为50左右,这将很快加载,尽管在此处将大小设置为500 x 500时,创建网格需要大约5秒钟。我尝试用线创建网格,但是问题是我需要正方形,因为我打算更改所选正方形的颜色。有什么办法可以使它更有效?

1 个答案:

答案 0 :(得分:0)

我认为您创建的矩形超出了您的需要。以下两行:

for x in range(0, self.c.winfo_width()):
        for y in range(0, self.c.winfo_height()):

将创建504x504矩形=254016。如果将其缩小到仅填充当前屏幕,它将正常工作:

def createGrid(self, event=None):
    for x in range(0, int(self.c.winfo_width()/20+1)):
        for y in range(0, int(self.c.winfo_height()/20+1)):
            x1 = (x * self.pixel_width)
            x2 = (x1 + self.pixel_width)
            y1 = (y * self.pixel_height)
            y2 = (y1 + self.pixel_height)
            self.c.create_rectangle(x1,y1,x2,y2)
    self.c.update()