用户正在使用 Tkinter 创建一个文本框网格,但发现程序在 grid
函数的 entry
部分出现错误。他正在尝试创建一个 9x9 的网格,但不幸的是,他遭遇了错误。
以下是代码:
import Tkinter
from Tkinter import *
import tkMessageBox
def window():
main_window = Tkinter.Tk()
main_window.geometry("500x500")
main_window.wm_title("Sudoku Solver 2000gazillion")
main_window.mainloop()
def grid():
knownNumbers = [
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0]
]
for row in range(0,9):
for col in range(0,9):
entry = Entry(main_window, textvariable = knownNumbers[row][col])
entry[row][col].grid(row=row, column=col)
def goButtonAction():
tkMessageBox.showinfo("Horray!", 'Finished product goes here')
def goButton():
button=Button(main_window, text = "Solve it!", command = goButtonAction )
button.grid(row=10, column=0, columnspan = 9)
def main():
window()
grid()
goButton()
main() #run it up
错误如下:
Traceback (most recent call last):
File "C:/Windows/System32/temp", line 40, in <module> main() #run it up
File "C:/Windows/System32/temp", line 37, in main grid()
File "C:/Windows/System32/temp", line 25, in grid entry = Entry(main_window, textvariable = knownNumbers[row][col])
NameError: global name 'main_window' is not defined
2、解决方案
在此问题中,Python 脚本中的问题是 main_window
变量未正确定义。解决此问题的步骤如下:
- 导入
Tkinter
模块:
import Tkinter
- 定义
main_window
变量并将Tk
实例分配给它:
main_window = Tkinter.Tk()
- 使用
main_window
变量创建网格并添加文本框:
def grid():
knownNumbers = [
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0]
]
for row in range(0,9):
for col in range(0,9):
entry = Entry(main_window, textvariable = knownNumbers[row][col])
entry.grid(row=row, column=col)
以下是完整的修复代码:
import Tkinter
from Tkinter import *
import tkMessageBox
def window():
global main_window # Declare main_window as a global variable
main_window = Tkinter.Tk()
main_window.geometry("500x500")
main_window.wm_title("Sudoku Solver 2000gazillion")
main_window.mainloop()
def grid():
knownNumbers = [
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0]
]
for row in range(0,9):
for col in range(0,9):
entry = Entry(main_window, textvariable = knownNumbers[row][col])
entry.grid(row=row, column=col)
def goButtonAction():
tkMessageBox.showinfo("Horray!", 'Finished product goes here')
def goButton():
button=Button(main_window, text = "Solve it!", command = goButtonAction )
button.grid(row=10, column=0, columnspan = 9)
def main():
window()
grid()
goButton()
main() #run it up