2016-07-26 67 views
0

我想通過幾個獨立例程以順序方式顯示文件分析的進度狀態,因爲每個分析例程都需要一些時間。附帶的演示代碼顯示了我遇到的問題。問題是顯示只在分析結束後纔會更新?感謝您瞭解代碼爲什麼沒有做到以及如何解決它。注意:例程1 & 2位於2個獨立的.py文件中。Tkinter文本未按順序顯示

from Tkinter import * 
import tkFileDialog 
import tkMessageBox 
import routine1 
import routine2 
import sys 

class Analysis(Frame): 
    def __init__(self): 
     Frame.__init__(self) 
     self.text = Text(self, height=20, width=60) # 20 characters 
     self.pack() 

     scroll=Scrollbar(self) 
     scroll.pack(side=RIGHT, fill=Y) 
     scroll.config(command=self.text.yview) 
     self.text.config(background='white') 
     self.text.pack(expand=YES, fill=BOTH) 


    def selectfile(self): 
     fname = tkFileDialog.askopenfilename() 
     self.text.delete(1.0, END) 
     self.text.insert(INSERT, ' working on routine 1: \n') 
     routine1.main(fname) 
     self.text.insert(INSERT, ' routine 1 done: \n') 
     self.text.insert(INSERT, ' working on routine 2: \n') 
     routine2.main(fname) 
     self.text.insert(INSERT, ' routine 2 done: ') 
     sys.exit() 

def main(): 
    tk = Tk() 
    tk.title('Data Analysis') 

    atext = Analysis() 
    atext.pack() 
    open_button = Button(tk, text="Select Data", 
    activeforeground='blue', command=atext.selectfile) 
    open_button.pack() 

    message=''' 
    Select file to be analysized 
    ''' 
    atext.text.insert(END,message) 
    tk.mainloop() 

if __name__ == "__main__": 
    main() 

routine1.py

import time 
def main(Filename): 
    print Filename 
    time.sleep(1) # to simulate process time 
    return 

routine2.py

import time 
def main(Filename): 
    print Filename 
    time.sleep(1) # to simulate process time 
    return 
+1

只有在控制權返回主循環完成後纔會更新Tkinter窗口。即使調用「睡眠」也不會讓窗口有機會更新。使用線程異步執行你的例程。 – Kevin

+0

@kevin:不,你不知道。 – martineau

回答

1

您需要在GUI上,改變的東西后調用update_idletasks()universal widget method手動更新顯示。請注意,上次更新只會在緊接其後的sys.exit()調用中顯示很短的時間。

def selectfile(self): 
     fname = tkFileDialog.askopenfilename() 

     self.text.delete(1.0, END) 
     self.text.insert(INSERT, ' working on routine 1: \n') 
     self.text.update_idletasks() 
     routine1.main(fname) 
     self.text.insert(INSERT, ' routine 1 done: \n') 
     self.text.update_idletasks() 

     self.text.insert(INSERT, ' working on routine 2: \n') 
     self.text.update_idletasks() 
     routine2.main(fname) 
     self.text.insert(INSERT, ' routine 2 done: ') 
     self.text.update_idletasks() 
     sys.exit() 
+0

謝謝先生,它的工作原理,輝煌的答案! – user4789322

+0

不客氣。順便說一句,您可以在最後一次更新後使用名爲'after()'的另一個通用窗口小部件方法添加延遲(並傳遞它不帶回調函數)。也請閱讀[_當有人回答我的問題時我應該怎麼做?](http://stackoverflow.com/help/someone-answers) – martineau