python的tk界面打开文件夹,显示里面的txt目录,然后在tk界面中阅读相应的txt文件
时间: 2024-03-21 07:37:42 浏览: 76
可以使用tkinter库来创建一个GUI界面,利用os库来获取文件夹中的txt文件列表,利用Text组件来显示文件内容。以下是一个简单的示例代码:
```python
import os
import tkinter as tk
from tkinter import filedialog, Text
root = tk.Tk()
root.title("File Explorer")
apps = []
def add_app():
for widget in frame.winfo_children():
widget.destroy()
filename = filedialog.askopenfilename(initialdir="/", title="Select File", filetypes=(("Text Files", "*.txt"),))
apps.append(filename)
for app in apps:
label = tk.Label(frame, text=app, bg="white")
label.pack()
def read_file():
for widget in frame.winfo_children():
widget.destroy()
foldername = filedialog.askdirectory(initialdir="/", title="Select Folder")
txt_files = [f for f in os.listdir(foldername) if f.endswith('.txt')]
for txt_file in txt_files:
with open(os.path.join(foldername, txt_file), "r") as f:
text = f.read()
label = tk.Label(frame, text=text, bg="white")
label.pack()
canvas = tk.Canvas(root, height=500, width=500, bg="#263D42")
canvas.pack()
button_frame = tk.Frame(root, bg="white")
button_frame.place(relwidth=0.8, relheight=0.1, relx=0.1, rely=0.1)
open_file_button = tk.Button(button_frame, text="Open File", padx=10, pady=5, fg="white", bg="#263D42", command=add_app)
open_file_button.pack(side="left", padx=10)
open_folder_button = tk.Button(button_frame, text="Open Folder", padx=10, pady=5, fg="white", bg="#263D42", command=read_file)
open_folder_button.pack(side="left", padx=10)
frame = tk.Frame(root, bg="white")
frame.place(relwidth=0.8, relheight=0.6, relx=0.1, rely=0.3)
root.mainloop()
```
这个程序创建了一个GUI界面,包含了两个按钮,分别用于打开单个txt文件和打开txt文件所在的文件夹。当用户点击"Open File"按钮时,程序会调用add_app函数,让用户选择一个txt文件,并将其添加到apps列表中。当用户点击"Open Folder"按钮时,程序会调用read_file函数,让用户选择一个文件夹,并获取该文件夹中所有的.txt文件列表。程序会依次打开每个txt文件,并将其内容显示在GUI界面中。
阅读全文