import tkinter as tk
from tkinter import filedialog
def open_file():
# 打开文件对话框,让用户选择文件
file_path = filedialog.askopenfilename(filetypes=[("Text Files", "*.txt")])
if file_path: # 如果用户选择了文件
with open(file_path, 'r', encoding='utf-8') as file:
# 清空文本框内容
text_box.delete(1.0, tk.END)
# 读取文件内容并插入到文本框
content = file.read()
text_box.insert(tk.END, content)
# 创建主窗口
root = tk.Tk()
root.title("读取TXT文件")
# 创建一个按钮用于打开文件
btn_open = tk.Button(root, text="选择TXT文件", command=open_file)
btn_open.pack()
# 创建一个多行文本框用于显示文件内容
text_box = tk.Text(root, wrap=tk.WORD)
text_box.pack(fill=tk.BOTH, expand=1)
# 运行主循环
root.mainloop()
tkinter - 展示选中文件内容
最新推荐文章于 2024-07-30 10:53:26 发布