0

Here's my code: It gives me an error that b is used before assignment.

from Tkinter import *
mConsole=Tk()
words=StringVar()
b='_ I _ _ U _'
def c():
    if b=='_ I _ _ U _':
        b='C I _ C U _'
            words.set(b)

words.set(b)
word=Label(textvariable=words, font='Jokerman 20').grid(row=1,column=3 ,columnspan=4)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Ruth
  • 23
  • 3
  • 1
    It is, **in `c`** - presumably the full traceback refers to unbound locals? Please provide a [mcve] and the whole error. – jonrsharpe Aug 26 '15 at 16:04
  • Not totally related to your question, but: are you using a tutorial? – Kevin Aug 26 '15 at 16:06
  • if that is your full code, that is probably not going to be your only error--you have to call `mConsole.mainloop()` as well, and you haven't called `c()` anywhere. – Joseph Farah Aug 26 '15 at 16:15

1 Answers1

0

You need to globalize the variable with the global command. After any function declaration, globalize any variables you intend on using.

In this case, you just have to add:

global b

at the top of your function and your code should work.

from Tkinter import *
mConsole=Tk()
words=StringVar()
b='_ I _ _ U _'
def c():
    global b
    if b=='_ I _ _ U _':
        b='C I _ C U _'
        words.set(b)

words.set(b)
word=Label(textvariable=words, font='Jokerman 20').grid(row=1,column=3 ,columnspan=4)

This resource may help: http://www.python-course.eu/global_vs_local_variables.php

As a side note, I recommend more descriptive variable/function names.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Joseph Farah
  • 2,463
  • 2
  • 25
  • 36