每两行交错设置一个tkinter网格

2024-06-17 09:27:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这里使用这个grid.py着色程序https://scipython.com/blog/a-simple-colouring-grid/生成网格的相关代码是

self.cells = []
for iy in range(n):
    for ix in range(n):
        xpad, ypad = pad * (ix+1), pad * (iy+1)
        x, y = xpad + ix*xsize, ypad + iy*ysize
        rect = self.w.create_rectangle(x, y, x+xsize,
                                   y+ysize, fill=UNFILLED)
        self.cells.append(rect)

我想知道我是否可以得到它,使方块交错如下所示: Staggered boxes


Tags: inpyrectselfforrangegridix
2条回答

您可以使用生成器函数为每条线生成坐标和每个单元格的填充。
row % 4 < 2:这是为连续行生成相同填充图案的原因,这些行
您可以轻松地调整以下代码示例以适应Grid class

enter image description here

import tkinter as tk


WIDTH, HEIGHT = 300, 300


def line_fills(row, numcells):
    """yields the fill value of each cells of a line, from 
    the row position of the line 
    """
    fill = True if row % 4 < 2 else False   # note %4: this is what generates identical fill pattern for consecutive rows the rows 
    for _ in range(numcells):
        yield fill
        fill = not fill


def line_coords(row, numcells, side):
    """yields the rectangle coordinates of each cells in a line, from 
    the row position of the line 
    """
    y0, y1 = row * side, (row+1) * side
    for col in range(numcells):
        x0, x1 = col * side, (col+1) * side
        yield x0, y0, x1, y1


def staggered_grid(canvas):
    """generates and draws a staggered grid on a canvas
    """
    side = 10
    w, h = WIDTH // side + 1, HEIGHT // side + 1
    fills = ['', 'grey']
    for row in range(h):
        for coord, fill in zip(line_coords(row, w, side), line_fills(row, w)):
            fill = 'grey' if fill else ''
            canvas.create_rectangle(*coord, fill=fill)

root = tk.Tk()
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT)
canvas.pack()

staggered_grid(canvas)

root.mainloop()

以下是基于您的代码的示例(添加缺少的部分):

import tkinter as tk

class App(tk.Tk):
    def __init__(self):
        super().__init__()
        ### added missing parts
        pad = 0
        xsize = ysize = 30
        n = 8

        self.w = tk.Canvas(self, width=(xsize+pad)*n+pad+1, height=(ysize+pad)*n+pad+1, highlightthickness=0)
        self.w.pack()
        ###
        self.cells = []
        for iy in range(n):
            for ix in range(n):
                xpad, ypad = pad * (ix+1), pad * (iy+1)
                x, y = xpad + ix*xsize, ypad + iy*ysize
                color = 'white' if (iy//2+ix)%2 else 'gray'
                rect = self.w.create_rectangle(x, y, x+xsize, y+ysize, fill=color) # use color instead of UNFILLED
                self.cells.append(rect)

app = App()
app.mainloop()

结果是:

enter image description here

相关问题 更多 >