tkinter:askopenfile打开文件报错UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xac in position 22: ille

第一步:ctrl+鼠标左键点击askopenfile进入源码

e50a31a1a9f84cd5abccd865d0045f5c.png

 第二步:找到如下图代码位置,添加编码格式

799af0870d254c7b8cda640fc9d44f10.png

 重新运行就不会报错了

这个错误提示表明在读取文件时使用了错误的编码格式。根据你的错误提示,使用的是GBK编码格式,但在文件中的某个位置存在无法解码的字节。 要解决这个问题,你可以尝试指定正确的编码格式,或者使用更通用的编码格式如UTF-8来读取文件。 以下是一个示例代码,展示了如何在读取文件时指定UTF-8编码格式: ```python from tkinter import * import os def read_file(): desktop_path = os.path.join(os.path.expanduser("~"), "Desktop") file_path = os.path.join(desktop_path, "input.txt") with open(file_path, "r", encoding="utf-8") as file: content = file.read() text_box.delete("1.0", "end") text_box.insert("1.0", content) def write_file(): content = text_box.get("1.0", "end-1c") desktop_path = os.path.join(os.path.expanduser("~"), "Desktop") file_path = os.path.join(desktop_path, "output.txt") with open(file_path, "w", encoding="utf-8") as file: file.write(content) root = Tk() text_box = Text(root) text_box.pack() read_button = Button(root, text="读取", command=read_file) read_button.pack() write_button = Button(root, text="写入", command=write_file) write_button.pack() root.mainloop() ``` 在这个示例中,我们在使用`open()`函数打开文件时,显式地指定了编码格式为UTF-8(`encoding="utf-8"`)。这样可以确保在读取和写入文件时使用正确的编码格式,避免出现解码错误。 你可以根据实际情况修改编码格式,例如使用GBK编码(`encoding="gbk"`)或其他适合你的编码格式。 运行这段代码,然后点击读取按钮,就可以将桌面上的txt文件的内容读取到文本框中,而且不会出现解码错误。点击写入按钮,可以将文本框中的内容写入到指定的txt文件中。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值