有效地在tkinter中创建网格



我当前正在使用以下代码来创建一个使用TKINTER模块

的窗口大小的网格。
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秒钟的时间才能创建网格。我尝试使用线条创建网格,但是问题是我需要正方形,因为我打算更改所选择的正方形的颜色。有什么办法可以使它更有效?

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

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()

最新更新