使用Tkinter开发数独游戏时重置函数仅清空最后一行Entry问题求助
Hey there! I see the issue with your Sudoku reset function—let's break it down and fix it quickly.
The Root Problem
The bug comes from how you're initializing your 2D lists col and val. When you use:
col = [[None]*cols]*rows val = [[IntVar]*cols]*rows
You're not creating 9 independent rows of lists. Instead, all 9 rows are references to the same underlying list. That means when you loop through and assign col[i][j] = Entry(...), you're actually overwriting the same list 9 times. By the end of your loop, every col[i] points to the last row's entries. So when your reset() function runs, it's just clearing that one shared list (which looks like only the last row gets cleared).
The Fix
Replace those 2D list initializations with list comprehensions, which create a new list for each row:
col = [[None for _ in range(cols)] for _ in range(rows)] val = [[IntVar() for _ in range(cols)] for _ in range(rows)]
Notice we also call IntVar() instead of just referencing the class—since each entry needs its own IntVar instance, not a reference to the same class object.
Modified Full Code
Here's your code with the fixes applied (changes marked with # FIXED):
def reset(): for i in range(rows): for j in range(cols): col[i][j].delete(0, "end") from Tkinter import Tk, Canvas, Entry, Button, CENTER, IntVar root = Tk() screen = Canvas(root, height = 430, width = 460) screen.pack() screen.create_text(200, 15, text = 'SUDOKU', font = 'calibri 20 bold') screen.create_line(127, 54, 127, 408) screen.create_line(232, 54, 232, 408) screen.create_line(24, 170, 336, 170) screen.create_line(24, 290, 336, 290) check_button = Button(root, text = 'Check', font = 'Calibri 10 bold', bd = 0, bg = 'Green', fg = 'white', padx = 10, pady = 5) screen.create_window(400, 70, window = check_button) reset_button = Button(root, text = 'Reset', font = 'Calibri 10 bold', bd = 0, bg = 'Red', fg = 'white', padx = 10, pady = 5, command = reset) screen.create_window(400, 110, window = reset_button) x, y, n = 0, 0, 0 cols, rows, values = 9, 9, 81 # FIXED: Use list comprehensions to create independent rows col = [[None for _ in range(cols)] for _ in range(rows)] val = [[IntVar() for _ in range(cols)] for _ in range(rows)] for i in range(rows): x = 0 if i == 0: y += 70 else: y += 40 for j in range(cols): x += 40 col[i][j] = Entry(root, width = 2, font = 'Calibri 20', bd = 0, justify = CENTER) screen.create_window(x, y, window = col[i][j]) x -= 5 root.mainloop()
Why This Works
List comprehensions generate a new list for each row, so each col[i] is a separate list of Entry widgets. Now when your reset() function loops through every col[i][j], it's accessing the correct Entry for each cell, not just the ones in the last row.
内容的提问来源于stack exchange,提问作者Aakash

