Captain Anonymous
Captain Anonymous

Reputation: 142

Update label elements in Tkinter

I have the following code:

import tkinter
from random import randint
score = 0
window = tkinter.Tk()

def Validate():
    global score
    answer_string = answer.get()
    try:
        answer_value = int(answer_string)
    except ValueError as e:
        print(e)
        return

if answer_value == number1 * number2:
    score -= 1
    print('True')
    q.pack_forget()
else:
    score += 1
    print('False')
i=0
while i==0:
    number1 = randint(1,12)
    number2 = randint(1,12)
    q = tkinter.Label(window, text="What is " + str(number1) + "x" + str(number2) + " ?")
    q.pack()
    answer = tkinter.Entry(window)
    submit = tkinter.Button(window, text = "Submit", command=Validate)
    answer.pack()
    submit.pack()
    window.mainloop()

What I'm trying to do is replace the text in q every time a question is asked. What I'm trying to do is remove q inside the validate function and then re-create it every time the code loops, but that doesn't work.

Any help would be appreciated.

Upvotes: 3

Views: 2952

Answers (1)

omri_saadon
omri_saadon

Reputation: 10621

Basically you don't need to create the Label each iteration, there are several ways of how to update Label in tkinter.

For example:

1.

window = tkinter.Tk()
text = tkinter.StringVar()
text.set('old')
lb = tkinter.Label(window, textvariable=text)
...
text.set('new')

2.

lb = tkinter.Label(window, text="What is " + str(number1) + "x" + str(number2) + " ?")
lb['text'] = 'new'

3.

lb = tkinter.Label(window, text="What is " + str(number1) + "x" + str(number2) + " ?")
lb.config(text='new')

Upvotes: 5

Related Questions