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

问题描述 投票:-1回答:1
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的列表中每次插入都有一个短暂的延迟。它似乎只是一次显示出来。我怎样才能做到这一点?

python tkinter
1个回答
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()
© www.soinside.com 2019 - 2024. All rights reserved.