马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
在用tkinter做小甲鱼视频35课的第二题时,比较text中内容是否较原文件中内容发生改变,如果没有发生改变,点“OK”按钮应该就什么事都不会发生,但是我每次点都跳转到发生改变的那里去了。。。。
按理来说text的get方法中有\n,文件的read方法也有\n,两者应该是一样的啊,不知道哪里出了问题。
C:\Users\Administrator\Desktop\1.pngimport tkinter as tk
import tkinter.filedialog
import tkinter.scrolledtext
#创建主窗体
window = tk.Tk()
window.title("显示文件内容")
window.geometry("500x400")
#label和button的建立,并加入frame中
frm = tk.Frame(window)
frm.pack(fill = "x")
var = tk.StringVar()
l = tk.Label(frm, textvariable = var )
l.pack(side = "left", padx = 5, pady = 5)
def surf():
file_name = tk.filedialog.askopenfilename()
var.set("文件【%s】的内容如下:" % file_name)
#将文件导入entry
global f #不设置全局变量后面没法引用
f = open(file_name, "r+")
for eachline in f.readlines():
st.insert("insert", eachline)
b1 = tk.Button(frm, text = "浏览文件", command = surf)
b1.pack(side = "right", pady = 5, padx = 5)
#增强功能
def change():
#此处需要去除get方法中自带的换行符吗?
new_string = st.get(0.0, "end")
if new_string != f.read():
#设置子窗口
window_child = tk.Toplevel(window)
window_child.geometry("400x150")
window_child.title("警告")
l_child = tk.Label(window_child, text = "检测到文件内容发生改变,请选择以下操作:")
l_child.pack(side = "top", padx =20, pady = 20)
#安装三个并列的button
def cover_save():
f.seek(0)
f.write(st.get(0.0, "end"))
f.close()
window_child.destroy()
b_child1 = tk.Button(window_child, text = "覆盖保存", command = cover_save)
b_child1.place(x = 50, y = 75)
def not_save():
f.close()
window_child.destroy()
b_child2 = tk.Button(window_child, text = "放弃保存", command = not_save)
b_child2.place(x = 150, y = 75)
def elsewhere_save():
f_elsewhere_name = tk.filedialog.asksaveasfilename()
f_elsewhere = open(f_elsewhere_name, "w")
f_elsewhere.write(st.get(0.0, "end"))
f_elsewhere.close()
f.close()
b_child3 = tk.Button(window_child, text = "另存为", command = elsewhere_save)
b_child3.place(x = 250, y = 75)
b2 = tk.Button(frm, command = change, text = "OK")
b2.pack(side = "right", pady = 5, padx = 5)
#scrolledtext
st = tk.scrolledtext.ScrolledText(window, width = 45)
st.pack(pady = 10)
window.mainloop()
|