简体   繁体   中英

Tkinter text not displayed in order

I wanted to display the progress status of a file analysis by a few independent routines in a sequential manner, as each analysis routine takes some time. The attached demo code shows the problem I had. The problem is that the display only gets updated after the analyses are over? Appreciate to know why the code is no doing what is intended and how to fix it. Note: routine1 & 2 are in 2 separate .py files.

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

You need to update the display manually by calling the update_idletasks() universal widget method after changing something in the GUI. Note that the last update will only be visible for a very short time because of the sys.exit() call immediately following it.

   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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM