新手求助!!!关于第35课的课后题
import easygui as gimport os
file = g.fileopenbox(default = '*.txt')
with open(file) as f:
title = os.path.basename(file)
msg = '文件【%s】内容如下:'% title
text = f.read()
text_after = g.textbox(msg,title,text)
if text != text_after:
choice = g.buttonbox('检测到文件内容改变,请选择操作:','警告',('覆盖保存','放弃保存','另存为'))
if choice == '覆盖保存':
with open (file,'w')as f:
f.write(text_after)
if choice =='放弃保存':
pass
if choice =='另存为':
another_path = g.filesavebox(default = '.txt')
if os.path.splitext(another_path)!='.txt':
anotner_path +='.txt'
with open (another_path,'w')as newfile:
newfile.write(text_after)
原先的text != text_after[:-1] 已经改成 text != text_after 了,新的问题出现了,为什么文档打开后在无任何修改的情况下选择Cancel,还会弹出“检测到文件内容改变”呢???{:10_277:}
因为如果选择 Cancel 选项,那么 textbox 就会返回 None ,导致text != text_after
你需要在 if text != text_after 之前加个 if 判断 text_after 是否为 None,若为就退出程序反之继续程序
另外你最后 anotner_path 变量名错了 改成 another_path
参考代码:
import easygui as g
import os
file = g.fileopenbox(default = '*.txt')
with open(file) as f:
title = os.path.basename(file)
msg = '文件【%s】内容如下:'% title
text = f.read()
text_after = g.textbox(msg,title,text)
if text_after == None:
exit()
if text != text_after:
choice = g.buttonbox('检测到文件内容改变,请选择操作:','警告',('覆盖保存','放弃保存','另存为'))
print(choice)
if choice == '覆盖保存':
with open (file,'w')as f:
f.write(text_after)
if choice =='放弃保存':
pass
if choice =='另存为':
another_path = g.filesavebox(default = '.txt')
if os.path.splitext(another_path)!='.txt':
another_path +='.txt'
with open (another_path,'w')as newfile:
newfile.write(text_after) Twilight6 发表于 2021-5-15 08:33
因为如果选择 Cancel 选项,那么 textbox 就会返回 None ,导致text != text_after
你需要在 if tex ...
啊原来如此,多谢!
页:
[1]