from Tkinter import * # Import all definitions from tkinter
import tkMessageBox # import tkinter.messagebox
from CheckSudokuSolution import isValid
class SudokuGUI:
def __init__(self):
window = Tk()
window.title("Check Sudoku Solution") # Set title
frame = Frame(window)
frame.pack()
self.cells = [] #A list of variables tied to entries
for i in range(9):
self.cells.append([])
for j in range(9):
self.cells[i].append(StringVar())
for i in range(9):
for j in range(9):
Entry(frame, width = 2, justify = RIGHT,
textvariable = self.cells[i][j]).grid(\
row = i, column = j)
Button(window, text = "Validate",
command =self.validate).pack()
window.mainloop() # Create an event loop
# Check if the numbers entered are a valid solution
def validate(self):
# Get the numbers from the entries
values = [[x.get \
for x in self.cells[i]] for i in range(9)]
if isValid(values):
tkMessageBox.showinfo("Check Sudoku Solution",
"The solution is valid")
else:
tkMessageBox.showwarning("Check Sudoku Solution",
"The Solution is invalid")
SudokuGUI() # Create GUI
函数isValid(grid)判断网格中的值是否为空。它检测网格中是否所有值都在1 到 9 之间以及每个值是否合法。
如何定位盒子中的单元?对于任意的grid[i][j],包含grid[i][j]的3*3的盒子第一个单元是grid[(i // 3) * 3][(j // 3) * 3]。如果grid[r][c]是一个3*3盒子的起始单元,那么这个盒子中的所有单元可以通过下面的嵌套循环来遍历。
'''
Get all cells in a 3-by-3 box starting at grid[r][c]
'''
for row in range(r, r+3)
for col in range(c, c+3)
# grid[row][col] is in the box
摘自 Y. Daniel Liang《Introduction to Programming Using Python 3》