从数组添加时间延迟到列表框(Tkinter)

时间:2017-12-16 20:50:50

标签: python tkinter

import tkinter
from tkinter import *
import time

tclean = tkinter.Tk()
tclean.title("TempCleaner")
tclean.resizable(width=False,height=False)
frame = Frame(tclean,width ="400",height="100")

scrollbar = Scrollbar(tclean)

scrollbar.pack( side = RIGHT, fill = Y ,expand =FALSE)

db = Button (tclean,text="Discover")

cb = Button (tclean, text="Clean")

list = Listbox (tclean, width="50",height="20", yscrollcommand = scrollbar.set)


path1='random'
f=[]
try:
   for(dirpath,dirnames,filenames) in walk(path1):
      f.extend(filenames)
      break
   except Exception:
      pass

def displayFiles():
   for x in range(0,len(f)):
      list.insert(x,f[x])
      time.sleep(.1)

我尝试在tkinter列表中每次插入都有一个短暂的延迟。它似乎只是一次显示出来。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以使用root.after()执行一项功能,该功能会将一项添加到Listbox并稍后使用after()

执行
import tkinter as tk
import os

def get_files(path):

    files = []

    try:
       for rootpath, dirnames, filenames in os.walk(path):
          files.extend(filenames)
          break
    except Exception as ex:
       print(ex)

    return files

def add_file():
    global index

    if index < len(files):
        lb.insert('end', files[index])
        index += 1
        root.after(100, add_file)

def discover():
    global files

    print('discover')

    files = get_files('Desktop/')

    index = 0
    add_file()

def clean():
    global index

    print('clean')

    lb.delete(0, "end")
    index = 0

# --- main ---

files = []

root = tk.Tk()
frame = tk.Frame(root, width="400", height="100")

scrollbar = tk.Scrollbar(root)
scrollbar.pack(side='right', fill='y', expand=False)

db = tk.Button(root, text="Discover", command=discover)
db.pack()
cb = tk.Button(root, text="Clean", command=clean)
cb.pack()

lb = tk.Listbox(root, width="50", height="20", yscrollcommand=scrollbar.set)
lb.pack()

root.mainloop()