我正在使用python和tkinter构建一个简单的GUI,它是一个Magic 8 Ball问题。当我在ASK函数内部尝试更新响应标签显示的文本时,我的问题出现了。我想尝试更新几次,以便在给出答案之前在---和“[空白]”之间闪烁几秒钟。但它似乎只是覆盖旧文本的新文本,直到ASK函数完成,此时要放在那里的最后一个文本是唯一剩下的文本。
这只是因为我只能在函数内部更新一次吗?或者有一个简单的方法吗?
代码,尽可能地删除以显示错误:
import time
import random
from tkinter import *
responses=[]
responses.append("No")
responses.append("Yes")
responses.append("I don't think so")
class TheGUI:
def __init__(self, master):
self.master = master
master.title("Python Magic 8 Ball GUI")
self.label = Label(self.master, text="Enter a Question you would like to ask (no to quit):")
self.label.pack()
self.enterplace = Entry(self.master)
self.enterplace.pack()
self.labeltext=StringVar()
self.labeltext.set("--")
self.response = Label(self.master, justify=CENTER, textvariable=self.labeltext)
self.response.pack()
self.frame = Frame(self.master)
self.frame.pack()
self.greet_button = Button(self.frame, text="Ask", command=self.ask)
self.greet_button.pack(side=LEFT)
self.close_button = Button(self.frame, text="Clear", command=self.clear)
self.close_button.pack(side=LEFT)
# This is the function in question
def ask(self):
the_q = self.enterplace.get()
if the_q == "no":
self.labeltext.set("Okay, Goodbye..")
time.sleep(2)
self.master.quit
else:
self.labeltext.set("Let me think for a moment")
self.master.update_idletasks()
time.sleep(2)
# Here, when I update the label to be ---, the previous text
# remains as a background, and only disappears once this
# function has exited. I was initially trying to make the ---
# blink once or twice, but ran into this error
self.labeltext.set("---")
self.master.update_idletasks()
time.sleep(2)
self.labeltext.set(random.choice(responses))
self.master.update_idletasks()
time.sleep(2)
def clear(self):
self.labeltext.set("")
self.master.update_idletasks()
root = Tk()
my_gui = TheGUI(root)
root.mainloop()
下图显示文字叠加,“让我想一想”和“我不这么认为”
答案 0 :(得分:1)
你几乎一切都正确!对我有用的是用self.master.update_idletasks()
self.master.update()
self.labeltext.set("Let me think for a moment")
self.master.update()
# self.master.update_idletasks()
time.sleep(2)
self.labeltext.set("---")
self.master.update()
# self.master.update_idletasks()
time.sleep(2)
self.labeltext.set(random.choice(responses))
self.master.update()
# self.master.update_idletasks()
time.sleep(2)
但是,我不明白为什么update_idletasks()
在这种情况下不起作用......
答案 1 :(得分:1)
你应该使用:
self.master.update()
而不是:
self.master.update_idletasks()
你很高兴。 至少它适用于Python 2.7