【发布时间】:2020-05-18 17:43:40
【问题描述】:
我正在尝试创建一个数独求解器。此时我的网格中有条目,但我不知道如何获取用户输入的值。
我还不知道如何制作数独求解器,但我认为我首先必须找到一种方法将输入存储在一些变量中,以便以后使用它们.
所以我的问题是,如何获取已填写到条目中的值?
这是我目前的代码:
from tkinter import *
root = Tk()
root.title('Sudoku Solver')
root.geometry('500x400')
mylabel = Label(root, text='Fill in the numbers and click solve').grid(row=0, column=0, columnspan=10)
# Create the grid
def beg():
global e
cells = {}
for row in range(1, 10):
for column in range(1, 10):
if ((row in (1,2,3,7,8,9) and column in (4,5,6)) or (row in (4,5,6) and column in (1,2,3,7,8,9))):
kleur='black'
else:
kleur='white'
cell = Frame(root, bg='white', highlightbackground=kleur,
highlightcolor=kleur, highlightthickness=2,
width=50, height=50, padx=3, pady=3, background='black')
cell.grid(row=row, column=column)
cells[(row, column)] = cell
e = Entry(cells[row, column], width=4, bg='white', highlightthickness=0, fg='black', relief=SUNKEN)
e.pack()
# Tell the button what to do
def solve():
global e
test = e.get()
print(test)
# Create the buttons and give them a command
clearer = Button(root, text='Clear', command=beg)
solver = Button(root, text='Solve', command=solve)
# Locate the buttons
clearer.grid(row=11, column=3, pady=30)
solver.grid(row=11, column=7, pady=30)
# Run it for the first time
beg()
root.mainloop()
我也尝试将 e 更改为 e[row, column] 但这给了我一个语法错误。
【问题讨论】:
-
您必须将所有
Entries保留在列表中。您不能使用e = ...将许多元素保留在变量中。您需要e = []并使用e.append()。稍后您可以使用循环for item in e: print(e.get())获取值。如果您将保留在二维列表中,那么您可以使用e[row][col].get()