|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
3. 在上一题的基础上增强功能:当用户点击“OK”按钮的时候,比较当前文件是否修改过,如果修改过,则提示“覆盖保存”、”放弃保存”或“另存为…”并实现相应的功能。
以下是我编写的代码:
import easygui as g
file_name = g.fileopenbox(msg = '请选择要阅读的文本文件:',title = '文本阅读程序')
with open(file_name,'r') as f:
file_content = f.read()
content = g.textbox(msg = '文件【%s】的内容如下:' % file_name,title = '显示文件内容:',text = file_content)
if file_content != content:
choice = g.buttonbox(msg = '检测到文件内容发生改变,请选择以下操作:',title = '警告',choices = '覆盖保存','放弃保存','另存为...')
if choice == '覆盖保存':
f = open(file_name,'w')
f.writelines(content)
f.close()
elif choice == '放弃保存':
return
elif choice == '另存为...':
new_location = g.filesavebox()
f2 = open(new_location,'w')
f2.writelines(content)
f2.close()
保存执行出现下图的问题,可我看不明白关键字参数的位置哪里错误,请大佬指点!
实际上,解决了表面的两个问题,你的代码还有两个问题:
1.选择文件窗口选择“取消”程序会出错;
2.显示文件内容选择“cancel”会错误认为文件内容改变,因为cancel后content为空;
所以还得加几个判断来解决这些问题:
- import easygui as g
- file_name = g.fileopenbox(msg = '请选择要阅读的文本文件:',title = '文本阅读程序')
- if file_name: #<---选“取消”file_name为空
- with open(file_name,'r') as f:
- file_content = f.read()
- content = g.textbox(msg = '文件【%s】的内容如下:' % file_name,title = '显示文件内容:',text = file_content)
- if content and file_content != content: #<---选"cancel"content为空
- choice = g.buttonbox(msg = '检测到文件内容发生改变,请选择以下操作:',title = '警告',choices = ('覆盖保存','放弃保存','另存为...'))
- if choice == '覆盖保存':
- f = open(file_name,'w')
- f.writelines(content)
- f.close()
- elif choice == '另存为...':
- new_location = g.filesavebox()
- f2 = open(new_location,'w')
- f2.writelines(content)
- f2.close()
复制代码
|
-
|