如何在tkinter中自动更新我的列表框?

时间:2015-04-02 12:29:05

标签: python python-3.x tkinter listbox

我发现了一些类似于我的问题的帖子,但不完全是这样,如果这是一个重复的问题,请道歉。

我使用tkinter读取文件夹,创建一个列出所有文件的列表框(它们都将成为.tif文件),并且用户选择他们想要查看的图像。不幸的是,文件将被添加和删除,所以我想自动更新我的列表框。这是我到目前为止的一些代码:

from tkinter import *
from PIL import Image, ImageTk
import os

file_path = "C:/Users/USX27512/Desktop/Python UI/Test_TIFFs"
root = Tk()

class Application(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        os.chdir(file_path)
        self.grid()
        self.canv = Canvas(self, relief=SUNKEN)
        self.canv.grid(row=2, column=1, columnspan=5, sticky=N)
        self.canv.config(width=500, height=500)
        self.canv.config(highlightthickness=0, background="black")
        self.view_files()

    def view_files(self):
        lb = Listbox(self, height=20)
        lb.update_idletasks()
        files = sorted(os.listdir(file_path), key=lambda x: os.path.getctime(os.path.join(file_path, x)))
        for file in files:
            if os.path.isfile(os.path.join(file_path, file)):
                lb.insert(END, file)

        lb.bind("<Double-Button-1>", self.on_double)
        lb.grid(row=2, column=0, sticky=NW)

    def on_double(self, event):
        widget = event.widget
        selection = widget.curselection()
        value = widget.get(selection[0])

        sbarV = Scrollbar(self, orient=VERTICAL)
        sbarH = Scrollbar(self, orient=HORIZONTAL)
        sbarV.config(command=self.canv.yview)
        sbarH.config(command=self.canv.xview)
        self.canv.config(yscrollcommand=sbarV.set)
        self.canv.config(xscrollcommand=sbarH.set)
        sbarV.grid(row=2, column=6, sticky=N+S)
        sbarH.grid(row=3, column=1, columnspan= 5, sticky=E+W)

        self.im = Image.open(value)
        image_width, image_height = self.im.size
        self.canv.config(scrollregion=(0, 0, image_width, image_height))
        self.im2 = ImageTk.PhotoImage(self.im)
        self.imgtag = self.canv.create_image(0,0, anchor=NW, image=self.im2)

app = Application(root)
root.mainloop()

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

我终于找到了答案here。从该功能,我可以检查列表并根据需要更新它。