Python基于用户选择文件生成QR码,扫码输出TextIOWrapper对象如何解决
问题根因
你调用filedialog.askopenfile()返回的是文件IO对象,不是文件路径也不是文件内容。你直接把这个对象传给qrcode.make()时,库会自动把对象转成字符串格式,就是你扫描出来的<_io.TextIOWrapper ...>那段内容。
根据你的实际需求,可以选择以下两种解决方案:
方案1:生成存储文件路径的二维码
如果你要让二维码扫描后展示选中文件的路径,直接用返回路径字符串的askopenfilename方法即可,修改后代码如下:
import qrcode from tkinter import * from tkinter import filedialog root = Tk() file_path = "" def choosefile(): global file_path file_path = filedialog.askopenfilename(title='Choose a File') choosefilebutton = Button(root, text='Choose a File', command=choosefile) choosefilebutton.pack() def submit(): if not file_path: return qr = qrcode.make(file_path) qr.save('qrcode.png') submit_button = Button(root, text='Submit', command=submit) submit_button.pack() root.mainloop()
方案2:生成存储文本文件内容的二维码
如果你要让二维码扫描后展示选中文本文件的内容,需要读取文件对象的内容再传入生成逻辑,修改后代码如下:
import qrcode from tkinter import * from tkinter import filedialog root = Tk() file_content = "" def choosefile(): global file_content file_obj = filedialog.askopenfile(mode='r', title='Choose a Text File', encoding='utf-8') if file_obj: file_content = file_obj.read() file_obj.close() choosefilebutton = Button(root, text='Choose a File', command=choosefile) choosefilebutton.pack() def submit(): if not file_content: return qr = qrcode.make(file_content) qr.save('qrcode.png') submit_button = Button(root, text='Submit', command=submit) submit_button.pack() root.mainloop()
注意:这个方案仅支持纯文本文件,二维码存储容量有限,不要传入大文件或者非文本类文件。
内容的提问来源于stack exchange,提问作者Charlie Zhang
相关产品推荐
相关产品推荐

