我正在嘗試構建一個數獨游戲。我的 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()
任何幫助表示贊賞。
uj5u.com熱心網友回復:
問題是
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/323742.html
標籤:Python 蟒蛇-3.x 特金特 tkinter 布局
