from tkinter import *
from tkinter.filedialog import *
root = Tk();root.geometry('400x200')
def test1():
f=askopenfilename(title='上传文件',initialdir='d:/file',filetypes=[('文件','.txt')])
show1['text']=f
Button(root,text = '选择编辑的文件',command = test1).pack()
show1=Label(root,width=40,height=3,bg='green')
show1.pack()
def test2():
with askopenfile(title='上传文件',
initialdir='d:file',filetypes=[('文件','.txt')]) as f:
show['text']=f.read()
Button(root,text='选择读取的文件',command=test2).pack()
show = Label(root,width=40,height=3,bg='green')
show.pack()
root.mainloop()
D:\pythonProject\venv\Scripts\python.exe D:/pythonProject/GUI/文件框.py
Exception in Tkinter callback
Traceback (most recent call last):
File "D:\Python2021\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "D:\pythonProject\GUI\文件框.py", line 19, in test2
show['text']=f.read()
UnicodeDecodeError: 'gbk' codec can't decode byte 0x98 in position 14: incomplete multibyte sequence
老师,我选择的文档里面内容是数字的话,读取就不会报错,里面是汉字就会报错,百度查找多次,让我加encoding=‘UTF-8’加了几次不同地方也一样报错