我有以下代码:
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()
我想要做的是每次询问问题时都替换q中的文字。我要做的是在validate函数中删除q,然后每次代码循环时重新创建它,但这不起作用。
任何帮助将不胜感激。
答案 0 :(得分:4)
基本上你不需要在每次迭代时创建Label,有几种方法可以在tkinter中更新Label。
例如:
<强> 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')