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])」,但這並沒有改變任何東西。
'import string;字母表= list(string.ascii_uppercase)'會少很多痛苦 – inspectorG4dget
對於這個問題,沒有理由首先有一個列表而不是字符串,因爲他需要做的就是索引它。 (循環遍歷'enumerate'會使它變得更簡單。) – abarnert
'enumerate'函數對字符串做了什麼?我找不到任何與字符串一起使用的示例。 – Guney