2014-01-28 91 views
2
#coding=utf-8 
'''Tkinter module''' 

from Tkinter import * 
import time 
root=Tk() 
t=Text(root,fg='red') 

t.pack() 
def insert_hello_into_text_area(): 
    t.insert(1.0,'Hello') 

Button(root,text='hello',command=insert_hello_into_text_area).pack() 

def start(): 
    i=0 
    while i<5: 
     t.insert(1.0,'Hello\n') 
     time.sleep(1) 
     i+=1 

Button(root,text='start',command=start).pack() 


root.mainloop() 

这是一个使用Tkinter模块的python程序。当我点击'开始'按钮时,我无法每秒都收到'hello'。相反,所有'你好'会在五秒钟后出现。那么如何在这个程序中一次显示'Hello'一次而不是显示5个'Hello'?如何显示'你好'每秒一次,而不是在这个程序中显示五个'你好'?

回答

4

而不是while循环与time.sleep,使用after

aftern(以下代码为1000)毫秒后调用回调。

def start(times=5): 
    t.insert(END, 'Hello\n') 
    if times > 1: 
     root.after(1000, lambda: start(times-1)) 
+0

如果我删除'lambda',为什么不起作用? – username123

+0

@fisiksnju,没有lambda'start(..)'被调用,不是在1000 ms以后,而是立即调用'start'函数的返回值作为回调函数,但它不是一个函数,而是'None' 。 – falsetru

+0

@fisiksnju,'after之后的第二个参数应该是一个可调用的对象。 (功能,方法,...) – falsetru

相关问题