-4

我在python中输入了一个变量,但它不会被接受。我不确定为什么会这样。我试图更改变量的名称,更改其名称的大小写,并更改函数的输入键。我的代码是:

import turtle   
startup = 1   
screen = turtle.Screen()      
screen.bgcolor("black")  
screen.bgpic("Assets/Title.png")   
screen.title("Game")  
def startgame():  
    if startup == 1:  
        screen.bgpic("Assets/Title_Two.png")  
    startup = 2  
turtle.listen()  
turtle.onkey(startgame, "Left")  

我得到的唯一错误信息是:

>>> Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:\Program Files (x86)\Python37-32\lib\turtle.py", line 686, in eventfun
    fun()
  File "C:\Users\Adam\OneDrive\Programming Stuff\Game\Game.py", line 9, in startgame
    if startup == 1:
UnboundLocalError: local variable 'startup' referenced before assignment
4

1 回答 1

0

将启动变成一个全局变量:

import turtle   
startup = 1   
screen = turtle.Screen()      
screen.bgcolor("black")  
screen.bgpic("Assets/Title.png")   
screen.title("Game")  
def startgame():
    global startup
    if startup == 1:  
        screen.bgpic("Assets/Title_Two.png")  
    startup = 2  
turtle.listen()  
turtle.onkey(startgame, "Left")  
于 2020-05-24T14:33:44.950 回答