Search code examples
pythonpython-3.xglobal-variables

How do I work around python's global variable problem


I am currently making a hangman game and I have a global variable that indicates which part of the hangman to draw. The problem is that I need to change the value of this variable (drawRate) within a function as I will need it in a different function later on but python will not let me do this. Is there any way I can work around this problem?

import tkinter as tk
import turtle
import string
from functools import partial
from draw_hangman import drawHangman

word = 'hello'
shown_text = list('-'*len(word))
draw = drawHangman()
drawRate = 0

def whenPressed(button, text):
    button.config(state = 'disabled')
    ind = []
    local_word = list(word)
    for i in local_word :
        if i == text:
            trash = local_word.index(i)
            ind.append(trash)
            local_word.pop(trash)
            local_word.insert(trash, '-')
    if len(ind) != 0:
        for i in ind:
            shown_text.pop(i)
            shown_text.insert(i, text)
        lab.config(text = ''.join(shown_text))
        for i in shown_text:
            if i == '-':
                trash = True
        if trash != True:
            print('You Won!')
    else:
        trash = draw[drawRate]
        exec(trash)
        drawRate+=1
        

root = tk.Tk()
t = turtle.Turtle()
alphabet = list(string.ascii_lowercase)
lab = tk.Label(root, text = '-'*len(word), font = (None, 15), width = 30)
lab.grid(row = 0, columnspan = 13)
for i in alphabet:
    btn = tk.Button(root, text=i)
    command = partial(whenPressed, btn, i)
    btn.config(command=command)
    row = (alphabet.index(i) // 13)+1
    column = alphabet.index(i) % 13
    btn.grid(row=row, column=column, sticky="news")

The variable draw is a list with the commands that draws the hangman figure:

draw = [
    '''t.penup()
t.fd(200)
t.rt(90)
t.fd(200)''',
    '''t.down()
t.lt(270)
t.fd(400)''',
    '''t.rt(90)
t.fd(400)''',
    '''t.rt(90)
t.fd(300)''',
    '''t.rt(90)
t.fd(75)
t.dot(75)''',
    't.fd(100)',
    '''t.lt(90)
t.fd(60)''',
    '''t.back(120)
t.fd(60)
t.rt(90)''',
    '''t.fd(75)
t.lt(30)
t.fd(100)''',
    '''t.back(100)
t.rt(60)
t.fd(100)''']

Solution

  • You have to declare this variable as global in the whenPressed() function like this:

    def whenPressed(button, text):
        global drawRate
        ...