に非ローカル使用カント:Python-グローバルを使用しています。これは私のコードであるPythonのタイピングゲーム
enter code here
def Game():
try:
tkMessageBox.showinfo("Hello!", "Welcome To my Game, %name")
root.destroy()
colors = ['Red', 'Blue', 'Green', 'Pink', 'Orange', 'Black', 'Yellow',
'White', 'Purple', 'Brown']
score = 0
timeLeft = 30
def startGame(event):
global timeLeft
if timeLeft == 30:
countdown()
nextColor()
def nextColor():
global score
global timeLeft
if timeLeft > 0:
e.focus_set()
if e.get().lower() == colors[1].lower():
score += 1
e.delete(0, Tkinter.END)
random.shuffle(colors)
label.config(fg=str(colors[1]), text=str(colors[0]))
scoreLabel.config(text="Score: " + str(score))
def countdown():
global timeLeft
if timeLeft > 0:
timeLeft -= 1
time.config(text="Time Left: " + str(timeLeft))
time.after(1000, countdown)
これは私がインデントしてプログラムを見た後
C:\Python27\python.exe D:/pythonaldecoa/TypingGameColor.py
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1542, in __call__
return self.func(*args)
File "D:/pythonaldecoa/TypingGameColor.py", line 17, in startGame
if timeLeft == 30:
NameError: global name 'timeLeft' is not defined
を得た誤りである、物事はより明確である: 「timeleftに」と 'score'はグローバルではなく、関数 'Game()'のローカルです。 ネストした関数nextColor()およびcountdown()でそれらを使用するには、グローバルではなく非ローカルとして宣言する必要があります。
あなたの質問は何ですか? – zipa
'Game'はクラスではなく関数ですか? –