python2 数独图形用户界面设计

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》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值