(python)tkinter中askopenfile打开文件错误解决办法

错误提示:

UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0x80 in position 15: illegal multibyte sequence

错误代码:

with askopenfile(title="打开文本文件") as f:
	self.textpad.insert(INSERT, f.read())

错误原因:

编码错误,所以要改变编码格式

代码修改:

with open(askopenfilename(title="打开文件"), encoding='utf-8') as f:
	self.textpad.insert(INSERT, f.read())

这样就能成功打开文件啦!!!

如果还是不能打开

有可能出现编码错误,这里就需要用一些小技巧,代码修改如下:

try:
	# 以GBK编码打开
	with open(askopenfilename()) as f:
		self.textpad.insert(INSERT, f.read()) # 插入文件内容
		self.filename = f.name # 获取文件名
except UnicodeDecodeError:
	# 以UTF-8编码打开
	with open(askopenfilename(), encoding='utf-8') as f:
		self.textpad.insert(INSERT, f.read())
		self.filename = f.name

猜你喜欢

转载自blog.csdn.net/weixin_45727931/article/details/108180223
今日推荐