2015-11-05 46 views
0
from tkinter import * 
from threading import Timer 
....... 

def getdata(dval): 
    global log,entryWidget,txtf,infile,lout 
    ff="c:\\downloads\test\logs\\log1.log" 
    flog=open(ff,encoding="utf-8") 
    infile= flog.read() 
    flog.close() 

def getlog(sval): 
    global log,entryWidget,txtf,infile,lout 
    txtf.delete ('1.0','end') 
    inf =entryWidget.get().strip() 
    if inf == "scan": 
     gdata = getdata("") 
     txtf.insert (END,gdata) 
    else: 
    gdata=str(datetime.now())+"\n" 
    txtf.insert (END,gdata) 
    gdata="" 

    ev=Timer(60,getlog,[lout]) 
    ev.start() 

def runscan(): 
    global log,entryWidget,txtf,infile,lout 
    root =Tk() 
    root.title("Scan log")t 
    textFrame = Frame(root) 
    txtf= Text(textFrame,width=60,height=18,font=("MS Sans Serif bold",8)) 
    entryWidget = Entry(textFrame) 

    textFrame.grid(row=200,column=200) 
    textFrame.bind("<Button-1>", getlog(lout) 

    txtf.grid(row=0,column=1) 

    entryWidget["width"] = 30 
    entryWidget.bind('<Return>',getlog(10)) 
    entryWidget.grid(row=25,column=1) 

    ev=Timer(60,getlog,[10]) 
    ev.start() 

    root.mainloop() 

if __name__ == "__main__": 
    runscan() 

定时器的Tkinter定时器使用正常工作,每隔60秒,但 Entrywidget没有。
如果我拿出计时器,Entrywidget工作正常。
因此,某处计时器线程会锁定窗口小部件输入。
似乎主循环中的定时器
需要重置功能,而不是getlog功能。与输入小

回答

2

您不需要使用Timer类。 Tkinter有将来运行代码的方法。 Timer类的问题在于它使用线程,而tkinter不是线程安全的。

下面是如何每60秒运行getlog的示例。调用一次,它会每分钟运行一次,直到程序退出。

def getlog(): 
    txtf.delete ('1.0','end') 
    inf =entryWidget.get().strip() 
    if inf == "scan": 
     gdata = getdata("") 
     txtf.insert (END,gdata) 
    else: 
     gdata=str(datetime.now())+"\n" 
     txtf.insert (END,gdata) 
    gdata="" 

    txtf.after(60000, getlog) 

注意,如果getdata("")可以阻止,这仍然会导致程序挂起。如果是这种情况,你将不得不继续使用线程,但你必须让你的线程获取数据并将其发布到线程安全队列,并让GUI线程轮询该队列。不知道getdata做什么,我不能更具体。

+0

感谢布莱恩将检查出来 –

+0

不工作entryWidget仍然挂起。 –

+0

@MNewton:那么,如果'getdata(“”)'可以阻塞,那么是的,这会导致你的程序挂起。由于您没有发布'getdata'的代码,因此无法确定。 –

0
def runscan(): 
    global log,entryWidget,txtf,infile,lout 
    lout=10 
    root =Tk() 
    root.title("Scan Mirc log") 
    root["padx"] = 2 
    root["pady"] = 2 
    root.configure(background='grey') 
    w = 400 # width for the Tk root 
    h = 360 # height for the Tk root 
    ws = root.winfo_screenwidth() # width of the screen 
    hs = root.winfo_screenheight() # height of the screen 
    x = ws - w-20 
    y = hs - h -60 
    root.geometry('%dx%d+%d+%d' % (w, h, x, y)) 
    textFrame = Frame(root) 
    entryWidget = Entry(root) 
    entryWidget["width"] = 30 

    txtf= Text(textFrame,width=65,height=23,font=("MS Sans Serif bold",8)) 

    textFrame.bind("<Button-1>",getlog,[lout]) 
    entryWidget.bind('<Return>',getlog,[lout]) 

    txtf.grid(row=0,column=1) 
    textFrame.grid(row=20,column=1) 
    entryWidget.grid(row=30,column=1) 

    txtf.after (60000,getlog,[lout]) 

    root.mainloop() 

if __name__ == "__main__": 
    runscan() 

清理它和纠正一些错误
,现在工作得很好