如何更有效地创建9x9网格? (Python,Tkinter)

时间:2017-12-29 19:25:05

标签: python python-3.x tkinter tkinter-canvas

我正在为数独拼图生成器创建一个9x9网格。 到目前为止,我已经为第一行帧创建了9个变量,并给出了9个变量网格行/列。我正在使用的代码如下。

我需要一种更有效的方法,因为我必须为网格创建81个这样的单元格。我怎样才能更有效/更好地做到这一点?请帮忙!

代码:

from tkinter import *

root = Tk()
root.title('Sudoku')
root.geometry('1000x1000')

# create all of the main containers
center = Frame(root, bg='white', width=900, height=900, padx=3, pady=3)

# layout all of the main containers
root.grid_rowconfigure(9, weight=1)
root.grid_columnconfigure(9, weight=1)
center.grid(row=1, sticky="nsew")

# create the center widgets
center.grid_rowconfigure(0, weight=1)
center.grid_columnconfigure(1, weight=1)

cell1 = Frame(center, bg='white', highlightbackground="black", highlightcolor="black", highlightthickness=1, width=100, height=100,  padx=3,  pady=3)
cell2 = Frame(center, bg='white', highlightbackground="black", highlightcolor="black", highlightthickness=1, width=100, height=100,  padx=3, pady=3)
cell3 = Frame(center, bg='white', highlightbackground="black", highlightcolor="black", highlightthickness=1, width=100, height=100,  padx=3, pady=3)
cell4 = Frame(center, bg='white', highlightbackground="black", highlightcolor="black", highlightthickness=1, width=100, height=100,  padx=3, pady=3)
cell5 = Frame(center, bg='white', highlightbackground="black", highlightcolor="black", highlightthickness=1, width=100, height=100,  padx=3, pady=3)
cell6 = Frame(center, bg='white', highlightbackground="black", highlightcolor="black", highlightthickness=1, width=100, height=100,  padx=3, pady=3)
cell7 = Frame(center, bg='white', highlightbackground="black", highlightcolor="black", highlightthickness=1, width=100, height=100,  padx=3, pady=3)
cell8 = Frame(center, bg='white', highlightbackground="black", highlightcolor="black", highlightthickness=1, width=100, height=100,  padx=3, pady=3)
cell9 = Frame(center, bg='white', highlightbackground="black", highlightcolor="black", highlightthickness=1, width=100, height=100,  padx=3, pady=3)

#create first row of grid

cell1.grid(row=0, column=0)
cell2.grid(row=0, column=1)
cell3.grid(row=0, column=2)
cell4.grid(row=0, column=3)
cell5.grid(row=0, column=4)
cell6.grid(row=0, column=5)
cell7.grid(row=0, column=6)
cell8.grid(row=0, column=7)
cell9.grid(row=0, column=8)

root.mainloop()

1 个答案:

答案 0 :(得分:1)

行的循环和列的循环。在字典中存储对小部件的引用:

cells = {}
for row in range(9):
    for column in range(9):
        cell = Frame(center, bg='white', highlightbackground="black",
                     highlightcolor="black", highlightthickness=1,
                     width=100, height=100,  padx=3,  pady=3)
        cell.grid(row=row, column=column)
        cells[(row, column)] = cell

通过上述内容,您可以通过cells dict引用任何小部件。例如,要将第3行第4列(从零开始计数)设置为红色,您可以执行以下操作:

cells[(3,4)].configure(background="red")