如何使用 Tkinter after() 方法? [英] How to use Tkinter after() method?

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

问题描述

我在使用 Tkinter 中的 after 方法时遇到问题.

I have a problem using the after method in Tkinter.

计划是以一秒的间隔打印i.我检查了 after 方法是否合适,但我不确切知道.

The plan is to print i with interval of one second. I checked whether the after method is suitable, but I don't know exactly.

这是代码.

# -*- coding: utf-8 -*-

from Tkinter import *
import time

root = Tk()
root.title("Program")
root['background'] ='gray'

def command_Print():
    for i in range(0, 10, 1):
        time.sleep(1)
        Label0.after(1)
        Labelvar.set(i)

Labelvar = StringVar()
Labelvar.set(u'original value')
Frame0 = Frame(root)
Frame0.place(x=0, y=0, width=100, height=50)
Label0 = Label(Frame0, textvariable=Labelvar, anchor='w')
Label0.pack(side=LEFT)


Frame_I = Frame(root)
Frame_I.place(x = 100, y = 0, width=100, height=70)
Button_I = Button(Frame_I, text = "Button" , width = 100, height=70, command = command_Print)
Button_I.place(x=0, y=0)
Button_I.grid(row=0, column=0, sticky=W, pady=4)
Button_I.pack()

root.mainloop()

推荐答案

不要在 Tkinter 应用程序中使用 time.sleep().使用 after() 让回调安排对自身的调用.

Don't use time.sleep() at all in Tkinter applications. Have the callback schedule a call to itself with after().

def command_Print(counter=0):
    Labelvar.set(counter)
    if counter < 10:
        root.after(1000, lambda: command_Print(counter+1))

另外,range(0, 10, 1) 就是 range(10).无需重复默认设置.

Also, range(0, 10, 1) is just range(10). There's no need to repeat the defaults.

这篇关于如何使用 Tkinter after() 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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