我已经搜索过,并尝试在我的应用程序中使用Tkinter中的.after命令,但我没有做任何事情来解决这个问题。无论我尝试做什么,我试图延迟的两个盒子同时出现。
submenu.add_command(label="View High Score", command=lambda: check_hs_file())
def check_hs_file():
hs_file = 'highscore.txt'
PATH = ('highscore.txt')
if os.path.isfile(PATH):
get_hs_as_int()
#go to main function
else:
with open(hs_file, 'w') as hs_file:
hs_file.write('0')
if os.path.isfile(PATH):
toplevel1 = Toplevel()
toplevel1.title("High Score!")
toplevel1.focus_set()
hs_textbox = Text(toplevel1, height=2, width=50)
hs_textbox.pack()
hs_textbox.insert(END, "You don't have a high score yet.. Creating file!\n")
get_hs_as_int()
else:
toplevel = Toplevel()
toplevel.title("High Score!")
toplevel.focus_set()
hs_textbox = Text(toplevel, height=2, width=50)
hs_textbox.pack()
hs_textbox.after(3000)
hs_textbox.insert(END, "Something went wrong, we could not create a file to keep your high score!")
def get_hs_as_int():
hs_file = 'highscore.txt'
with open(hs_file, 'r') as hs_file:
high_score = hs_file.read()
high_score = int(high_score)
toplevel = Toplevel()
toplevel.after(4000)
toplevel.title("High Score!")
toplevel.focus_set()
hs_textbox = Text(toplevel, height=2, width=50)
hs_textbox.pack()
hs_textbox.insert(END, "Your high score is: {}".format(high_score))
同样,打印高分的方框和检查是否有高分的方框同时出现。无论我在哪里添加.after到我的代码。真的很感激任何帮助!
答案 0 :(得分:0)
Tk.Widget.after
的通常语法将回调函数作为参数。
因此,要使用小片段作为示例,您可以写:
def method(...):
... # calculate the meaning of life
def callback():
print("I'm called later!")
self.after(10, callback) # execute callback() after 10s
更常见的是,你要做的是在类或模块中定义另一个函数或方法,然后在指定的时间之后传递给它。
因此,例如,如果您希望在窗口出现后不久显示弹出窗口,则可能会执行以下操作:
class Controller():
def __init__(self, master):
# perform some initial setup
master.after(5, self.finalise) # run self.finalise() after 5s
# do some more setup
def finalise(self):
tk.messagebox.showinfo('Called later', 'Yippeeeeeee!')