|
发表于 2023-7-30 22:32:55
|
显示全部楼层
本楼为最佳答案
 以下是一个使用Python Tkinter库实现的简单的文件浏览和文件内容显示程序:
- 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") as file:
- content.delete(1.0, tk.END)
- content.insert(1.0, file.read())
-
- def save_file():
- if file_path:
- with open(file_path, "w") as file:
- file.write(content.get(1.0, tk.END))
-
- def check_modified():
- if file_path and file_has_been_modified:
- choice = tk.messagebox.askquestion("File modified", "The file has been modified. Do you want to save your changes?")
- if choice == "yes":
- save_file()
- elif choice == "no":
- pass
- else:
- file_path = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=[("Text files", " *.txt")])
- if file_path:
- with open(file_path, "w") as file:
- file.write(content.get(1.0, tk.END))
-
- root = tk.Tk()
-
- file_path = None
- file_has_been_modified = False
-
- label = tk.Label(root, text="Select a text file to open:")
- label.pack()
-
- button = tk.Button(root, text="Open", command=open_file)
- button.pack()
-
- content = tk.Text(root)
- content.pack()
-
- label = tk.Label(root, text="")
- label.pack()
-
- button = tk.Button(root, text="Save", command=save_file)
- button.pack()
-
- label = tk.Label(root, text="")
- label.pack()
-
- button = tk.Button(root, text="Exit", command=root.quit)
- button.pack()
-
- root.mainloop()
复制代码
当用户点击“Open”按钮时,会弹出文件选择对话框,用户可以选择一个文本文件。文件选择后,文件内容会被读取并显示在文本框中。
当用户修改文本内容并点击“Save”按钮时,程序会检查文件是否已经被修改。如果文件已经被修改,程序会弹出一个对话框,询问用户是否要覆盖保存、放弃保存或者另存为。如果用户选择覆盖保存,程序会将文本框中的内容写入到原始文件中。如果用户选择放弃保存,程序会什么也不做。如果用户选择另存为,程序会弹出一个文件保存对话框,用户可以选择另存的文件名和路径。
当用户点击“Exit”按钮时,程序会退出。 |
|