尝试使用 tkinter 网格创建数独游戏,GUI 网格出现问题

Trying to create sudoku game using tkinter grid, got problem with the GUI grid

我正在尝试构建一个数独游戏。我的 GUI 有问题。游戏由 9 个方块组成,每个方块有 9 个单元格。但是我只能得到最后 3 个块。我错过了前 6 行。这是我得到的结果:

代码如下:

import tkinter as tk

root = tk.Tk()

# Create the puzzle
puzzle = tk.Frame(root, bg='white')
puzzle.pack()

# Add the 3 * 3 big blocks
blocks = [[None] * 3] * 3
for i in range(3):
    for j in range(3):
        blocks[i][j] = tk.Frame(puzzle, bd=1, highlightbackground='light blue',
                                highlightcolor='light blue', highlightthickness=1)
        blocks[i][j].grid(row=i, column=j, sticky='nsew')

# Add the 9 * 9 cells
btn_cells = [[None] * 9] * 9
for i in range(9):
    for j in range(9):
        # Add cell to the block
        # Add a frame so that the cell can form a square
        frm_cell = tk.Frame(blocks[i // 3][j // 3])
        frm_cell.grid(row=(i % 3), column=(j % 3), sticky='nsew')
        frm_cell.rowconfigure(0, minsize=50, weight=1)
        frm_cell.columnconfigure(0, minsize=50, weight=1)
        var = tk.StringVar()
        btn_cells[i][j] = tk.Button(frm_cell, relief='ridge', bg='white', textvariable=var)
        btn_cells[i][j].grid(sticky='nsew')

        # Show the index for reference
        var.set(str((i, j)))
        
root.mainloop()

感谢任何帮助。

问题是

blocks = [[None] * 3] * 3

它不会创建 3 个唯一的子列表,但会创建 3 个对同一列表的引用。

应该是

blocks = [[None for x in range(3)] for x in range(3)] 

我也会用

btn_cells = [[None for x in range(9)] for x in range(9)]

坦率地说,我会用不同的方式来写它——使用 apppend()

blocks = [] 
for r in range(3):  # `r` like `row`
    row = []
    for c in range(3):  # `c` like `column`
        frame = tk.Frame(puzzle, bd=1, highlightbackground='light blue',
                                highlightcolor='light blue', highlightthickness=1)
        frame.grid(row=r, column=c, sticky='nsew')
        row.append(frame)
    blocks.append(row)