有谁能用清晰奇特的思路来解决这道题
提供一个文件夹浏览框,让用户选择需要打开的文本文件,打开并显示文件内容。当用户点击“OK”按钮的时候,比较当前文件是否修改过,如果修改过,则提示“覆盖保存”、”放弃保存”或“另存为…”并实现相应的功能。 import tkinter as tk
import tkinter.filedialog as fd
root = tk.Tk()
root.withdraw()# 隐藏窗口
f = fd.askopenfilename(defaultextension=".txt", filetypes=[("文本文件", "*.txt")])
f = open(f, "r")
print(f)
f.close()
root.destory() 以下是一个使用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”按钮时,程序会退出。
页:
[1]