コード:
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])" を追加しようとしましたが、何も変わりませんでした。