Tkinter 命令忽略一些行 [英] Tkinter command ignores some lines

查看:39
本文介绍了Tkinter 命令忽略一些行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码创建了一个带有按钮的 Tkinter 根窗口.该按钮绑定到一个简单的函数,该函数应该立即显示一个进度条小部件.虽然打印语句按预期运行,但永远不会显示进度条.有什么线索吗?

The code below createds a Tkinter root window with a button. The button is bound to a simple function which should display a progressbar widget momentarily. Whilst the print statements run as expected, the progress bar is never displayed. Any clues?

from Tkinter import *
import ttk
from time import sleep

root = Tk()

def foo():
    print 'starting...'
    pb = ttk.Progressbar(root, mode='indeterminate')
    pb.pack()
    sleep(5)
    print 'stopping...'
    pb.destroy()

ttk.Button(root, text="Run", command=foo).pack()

推荐答案

解决方案如下:

from Tkinter import *
import ttk
from time import sleep

root = Tk()

def foo():
    print 'starting...'
    pb = ttk.Progressbar(root, mode='indeterminate')
    pb.pack()
    root.update()
    sleep(5)
    print 'stopping...'
    pb.destroy()

ttk.Button(root, text="Run", command=foo).pack()

root.mainloop()

现在是为什么:当某些函数调用之间有可用时间时,tkinter 刷新它的 GUI.因此,如果您想制作一个显示大型进程进度的界面,您必须定期手动调用 Tk.update() 方法.

Now the why : tkinter refresh it's GUI when there is available time between some function call. So if you want to make an interface that show the progress of a huge process you have to call periodically and manually the Tk.update() method.

实际上,在您的代码中,您正在执行 time.sleep(5),可以预期 Tkinter 将在睡眠期间更新 GUI,但这是一个活动"等待,因此 tkinter GUI 不会刷新.

In fact in your code you are doing a time.sleep(5), one can expect that Tkinter will update the GUI during the sleep, but this is an 'active' wait so the tkinter GUI is'nt refreshed.

这里提供了一种方法,通过每 25 毫秒移动一次进度条,让用户意识到正在发生的事情.如果没有关于 0.025(或其他合理值)的测试,进度条会发疯并且移动得太快.这个想法是不使用睡眠而是使用时间:

Here comes a way to make the user aware that something is happening by moving the progress bar every 25ms. If no test about the 0.025 (or other reasonable value), the progress bar go mad and move too quickly. The idea is to not use sleep but time instead :

from Tkinter import *
import ttk
from time import *

root = Tk()

def foo():
    print 'starting...'
    pb = ttk.Progressbar(root, mode='indeterminate')
    pb.pack()
    root.update()
    start = time()
    last_update= time()
    while (time() - start) <= 5:
        current = time()
        if (current-last_update)> 0.025:
            pb.step()
                root.update()
                last_update = current
    print 'stopping...'
    pb.destroy()

ttk.Button(root, text="Run", command=foo).pack()

root.mainloop()

这篇关于Tkinter 命令忽略一些行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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