在使用Tkinter创建了一个列表框,希望能够在列表框中显示一个子目录下的所有文件名。通过循环目录中的文件并使用print
函数输出文件名,能够在控制台中看到文件列表,但是无法在列表框中显示。
2、解决方案
1. 使用os
模块获取指定目录下的文件列表
import os
def get_booknames(directory):
"""
获取指定目录下的所有文件名
Args:
directory: 目录路径
Returns:
list: 文件名列表
"""
booknames = []
for file in os.listdir(directory):
if fnmatch.fnmatch(file, '*.txt'):
booknames.append(file)
return booknames
2. 将文件列表插入到列表框中
def insert_books(listbox, booknames):
"""
将文件列表插入到列表框中
Args:
listbox: 列表框控件
booknames: 文件名列表
"""
listbox.delete(0, "end")
for bookname in booknames:
listbox.insert("end", bookname)
3. 创建Tkinter界面并绑定事件
import tkinter as tk
root = tk.Tk()
root.title("Reader")
listbox = tk.Listbox(root, selectmode=tk.BROWSE)
listbox.pack()
label = tk.Label(root, text="Select a book")
label.pack()
def open_book():
"""
打开选中的书籍,将其内容显示到画布上
"""
selected_book = listbox.get(listbox.curselection())
with open(selected_book, "r") as f:
content = f.read()
canvas.delete("all")
canvas.create_text(10, 10, anchor="nw", text=content)
button = tk.Button(root, text="Open Book", command=open_book)
button.pack()
canvas = tk.Canvas(root, width=500, height=300)
scrollbar = tk.Scrollbar(root)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
canvas.pack()
# 将文件列表插入到列表框中
booknames = get_booknames("/txtbooks")
insert_books(listbox, booknames)
# 启动Tkinter事件循环
root.mainloop()
代码例子
import tkinter as tk
import os
import fnmatch
root = tk.Tk()
root.title("Reader")
listbox = tk.Listbox(root, selectmode=tk.BROWSE)
listbox.pack()
label = tk.Label(root, text="Select a book")
label.pack()
def get_booknames(directory):
"""
获取指定目录下的所有文件名
Args:
directory: 目录路径
Returns:
list: 文件名列表
"""
booknames = []
for file in os.listdir(directory):
if fnmatch.fnmatch(file, '*.txt'):
booknames.append(file)
return booknames
def insert_books(listbox, booknames):
"""
将文件列表插入到列表框中
Args:
listbox: 列表框控件
booknames: 文件名列表
"""
listbox.delete(0, "end")
for bookname in booknames:
listbox.insert("end", bookname)
def open_book():
"""
打开选中的书籍,将其内容显示到画布上
"""
selected_book = listbox.get(listbox.curselection())
with open(selected_book, "r") as f:
content = f.read()
canvas.delete("all")
canvas.create_text(10, 10, anchor="nw", text=content)
button = tk.Button(root, text="Open Book", command=open_book)
button.pack()
canvas = tk.Canvas(root, width=500, height=300)
scrollbar = tk.Scrollbar(root)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
canvas.pack()
# 将文件列表插入到列表框中
booknames = get_booknames("/txtbooks")
insert_books(listbox, booknames)
# 启动Tkinter事件循环
root.mainloop()