0

I'm writing a tkinter program, and I'm trying to update my label on the ui. However I can't get it to work. Here's the code:

from tkinter import *
import random, functools, string

root = Tk()

word_list = ["APPLE", "PEAR", "BANNANA"]

word = word_list [random.randint(0,2)]

hidden_word = ["_ "] * len(word)
print (word)


abc = ['_ '] * len(word)
guessed_letters = []

#Functions
def click_1 (key):
    if key in word:
        guessed_letters = ''.join([key])
        global abc
        abc = ''.join([key if key in guessed_letters else "_" for key in word])
    else:
        print ("Nope") ####TESTING#####


#Frames
hangman_frame = Frame(root)
hangman_frame.grid(row=0, column=0, sticky=N)
letter_frame = Frame(root)
letter_frame.grid(row=1, column=0, sticky=S)

#Label
letters_label = Label(hangman_frame, textvariable=abc)
letters_label.grid(row=0, column=0, sticky=W)

(Just an excerpt, not all)

My question is that when ran, this section appears not to work:

letters_label = Label(hangman_frame, textvariable=abc)

where:

abc = ['_ '] * len(word)
    guessed_letters = []

#Functions
def click_1 (key):
    if key in word:
        guessed_letters = ''.join([key])
        global abc
        abc = ''.join([key if key in guessed_letters else "_" for key in word])

And nothing shows up, whereas when this is put:

letters_label = Label(hangman_frame, text=abc)

The label shows up, but does not update when the function click_1 is called.

Any reason to this? Thanks in advance.

1 Answer 1

2

The reason is that the textvariable option requires an instance of StringVar or IntVar. You can't just pass it the name of a normal variable.

Generally speaking, you never need to use the textvariable option unless you specifically need the features of a StringVar or IntVar (such as having two widgets share the same data, or doing traces on the variable). I know lots of examples use it, but it just adds another object that you don't really need.

In order to update the text on a label, you would do this:

letters_label = Label(..., text="initial value")
...
def click_1(...):
    ...
    abc = ...
    letters_label.configure(text=abc)
Sign up to request clarification or add additional context in comments.

3 Comments

That works almost perfectly - it does not keep the changes, ie. when i press 'a', it changes to 'a', but when i press 'b', it only outputs 'b' and removes the 'a'. Any way to solve this?
can you please answer my question as it is frustrating me that it is doing this.
You must be replacing a with b instead of adding b to a when redefining abc before displaying it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.