使用 Tkinter 等待一定时间 [英] Waiting certain amount of time with Tkinter

查看:56
本文介绍了使用 Tkinter 等待一定时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Tkinter 程序,我想暂停 3 秒钟.time.sleep 不起作用,并且 after 方法不能完全按照我的意愿去做.

I have a Tkinter program which I want to pause for 3 seconds. time.sleep doesn't work and the after method doesn't do exactly what I want to.

这是一个示例代码:

from Tkinter import *
def waithere():
    print "waiting..."
root = Tk()

print "1"
root.after(3000,waithere)
print "2"

root.mainloop()

输出:

1
2
*3 seconds*
waiting...

我想要的输出:

1
waiting...
*3 seconds*
2

谢谢.

推荐答案

通常,让 GUI 等待某些事情是一个非常糟糕的主意.这并不意味着基于事件的程序如何工作.或者更准确地说,GUI 已经处于永久等待状态,您不想用自己的等待来阻止它.

Normally it's a very bad idea to have a GUI wait for something. That's imply not how event-based programs work. Or more accurately, GUIs are already in a perpetual wait state, and you don't want to block that with your own waiting.

话虽如此,tkinter 有一种方法可以等到某些事情发生.例如,您可以使用等待"功能之一,例如 wait_variablewait_windowwait_visibility.

That being said, tkinter has a way to wait until certain things happen. For example, you can use one of the "wait" functions, such as wait_variable, wait_window, or wait_visibility.

假设您希望 waithere 进行等待,您可以使用 wait_variable 进行等待,after 在给定的时间后设置变量.

Assuming that you wanted waithere to do the waiting, you could use wait_variable to do the waiting, and after to set the variable after a given amount of time.

这是基于您的原始代码的解决方案:

Here's the solution based on your original code:

from Tkinter import *
def waithere():
    var = IntVar()
    root.after(3000, var.set, 1)
    print("waiting...")
    root.wait_variable(var)

root = Tk()

print "1"
waithere()
print "2"

root.mainloop()

使用这些方法的优点是您的代码在等待时仍然能够响应事件.

The advantage to using these methods is that your code is still able to respond to events while it is waiting.

这篇关于使用 Tkinter 等待一定时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆