Python:Tkinter -- 如何让光标显示忙碌状态

问题描述 投票:0回答:2

我正在尝试让 Tkinter 显示繁忙的光标。不幸的是,我一定错过了一些非常明显的东西。以下是一个非常简单的程序,可以重现我的问题:

 from Tkinter import *
 import time

 def do_something():
     print "starting"
     window.config(cursor="wait")
     time.sleep(5)
     window.config(cursor="")
     print "done"
     return

 root = Tk()
 menubar = Menu(root)
 filemenu = Menu(menubar, tearoff=0)
 filemenu.add_command(label="Do Something", command=do_something)
 filemenu.add_command(label="Exit", command=root.quit)
 menubar.add_cascade(label="File", menu=filemenu)
 root.config(menu=menubar)
 root.mainloop()

我没有看到光标有任何变化

python tkinter
2个回答
8
投票

像这样制作

do_something

def do_something():
    print "starting"
    root.config(cursor="watch")
    root.update()
    time.sleep(5)
    root.config(cursor="")
    print "done"

基本上,我做了三件事:

  1. window
    替换为
    root
    (因为
    window
    未定义,并且
    root
    是窗口句柄)。

  2. 在配置光标的行后面添加了

    root.update()

  3. 删除了不必要的

    return
    (这不会导致任何错误,但为什么要有它?)。


0
投票

处理等待光标的更好方法是使用上下文管理器,这样您就不必担心关闭等待光标(例如出现异常或其他缓慢工作代码的提前退出)。

import contextlib

@contextlib.contextmanager
def WaitCursor(root):
    root.config(cursor="watch")
    root.update()
    try:
        yield root
    finally:
        root.config(cursor="")

然后用法如下

with WaitCursor(root):
    time.sleep(5)
© www.soinside.com 2019 - 2024. All rights reserved.