代码:
def createLetters(frame, startX, startY, width, height, spacing):
alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I",
"J", "K", "L", "M", "N", "O", "P", "Q", "R",
"S", "T", "U", "V", "W", "X", "Y", "Z"]
def letterAction(letter):
letter.destroy()
for i in range(0, 26):
if (i >= 9 and i <= 17):
y = startY + height + 2 * spacing
x = startX + ((width + spacing) * (i - 9))
elif (i >= 17):
y = startY + 2 * height + 3 * spacing
x = (width + spacing) / 2 + startX + ((width + spacing) * (i - 18))
elif (i <= 8):
y = startY + spacing
x = startX + ((width + spacing) * i)
exec(alphabet[i] + " = Button(" + frame + ", text = '" + alphabet[i] + "', command = letterAction(" + alphabet[i] + "))")
exec(alphabet[i] + ".place(x = " + str(x) + ", y = " + str(y) + ", width = " + str(width) + ", height = " + str(height) + ")")
错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter\__init__.py", line 1442, in __call__
return self.func(*args)
File "E:\Hangman\hangmanTk.py", line 106, in playScreen
createLetters("playFrame", 175, 250, 50, 50, 0)
File "E:\Hangman\hangmanTk.py", line 95, in createLetters
exec(alphabet[i] + " = Button(" + frame + ", text = '" + alphabet[i] + "', command = letterAction(" + alphabet[i] + "))")
File "<string>", line 1, in <module>
NameError: name 'A' is not defined
我正在尝试使用循环创建多个 tkinter 按钮。我可以很好地创建按钮,但我似乎无法为它们创建回调。当我尝试时,它告诉我我用于按钮的变量没有定义。我尝试在我定义按钮的地方添加“exec(”global“+alphabet[i])”,但这并没有改变任何东西。