Search code examples
pythontkinterglobal-variablesglobal

With one variable make another one bigger but make the first one smaller


I want to make it so when I upgrade the level goes up but the clicks go down by the upgrade cost but when I do it gives me this error:

line 19, in upgrade
    if clicks >= 10: UnboundLocalError: local variable 'clicks' referenced before assignment

Here's the code:

def counter():
    global clicks
    for i in range(0, level):
        clicks += 1
    score.config(text="Score: " + str(clicks))

def upgrade():
    global level
    if clicks >= 10:
        level += 1
        clicks -= 10
    levelLabel.config(text="Upgrade: " + str(level))

Solution

  • Do you see that global clicks at the beginning of the first function? You have to do it also in the other function, provided that a clicks variable exists in global scope.


    global x
    
    def foo():
        x = 42
    
    def bar():
        global x
        x = 42
    
    x = 69
    foo()
    print(x) # 69
    bar()
    print(x) # 42