【问题标题】:Tkinter text not displayed in orderTkinter 文本未按顺序显示
【发布时间】:2016-07-26 17:52:25
【问题描述】:

我想通过几个独立的例程按顺序显示文件分析的进度状态,因为每个分析例程都需要一些时间。随附的演示代码显示了我遇到的问题。问题是只有在分析结束后才更新显示?很高兴知道为什么代码没有做预期的事情以及如何修复它。注意:routine1 和 2 在 2 个单独的 .py 文件中。

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

【问题讨论】:

  • Tkinter 窗口仅在您执行的任何函数完全完成后控制返回到主循环时更新。甚至不调用sleep 也不会给窗口更新的机会。使用线程异步执行您的例程。
  • @kevin:不,你没有。

标签: python tkinter


【解决方案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()

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2022-01-23
  • 2022-10-24
  • 1970-01-01
  • 2018-03-05
  • 1970-01-01
  • 2018-11-29
  • 1970-01-01
  • 2018-03-26
相关资源
最近更新 更多