2015-11-05 80 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() 

清理它和糾正一些錯誤
,現在工作得很好