我有以下代码:
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,然后在每次代码循环时重新创建它,但这不起作用。
任何帮助都将不胜感激。
最佳答案
基本上不需要每次迭代都创建标签,有几种方法可以在tkinter中更新标签。
例如:
一
window = tkinter.Tk()
text = tkinter.StringVar()
text.set('old')
lb = tkinter.Label(window, textvariable=text)
...
text.set('new')
二
lb = tkinter.Label(window, text="What is " + str(number1) + "x" + str(number2) + " ?")
lb['text'] = 'new'
三。
lb = tkinter.Label(window, text="What is " + str(number1) + "x" + str(number2) + " ?")
lb.config(text='new')
关于python - 更新Tkinter中的标签元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43965856/