我正在尝试制作一个 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
我正在使用Python 2.7
您正在window()
函数中定义main_window
变量。这会将此变量的使用限制为 window()
函数。如果您希望它在任何地方都可用,例如,您可以在window()
函数之外定义它,例如
# Imports
main_window = Tkinter.tk()
def window():
main_window.geometry("500x500")
# Rest of your code