【问题标题】:I tried to make a QRcode from the user's input file with Python but its not working我试图用 Python 从用户的输入文件中制作一个二维码,但它不起作用
【发布时间】:2021-12-24 20:54:01
【问题描述】:

这是我的代码:

import qrcode
from tkinter import *
from tkinter import filedialog

root=Tk()

def choosefile():
    global file
    file=filedialog.askopenfile(mode='r',title='Choose a File')

choosefilebutton=Button(root,text='Choose a File',command=choosefile)
choosefilebutton.pack()

def submit():
    qr=qrcode.make(file)
    qr.save('qrcode.png')

choosefilebutton=Button(root,text='Submit',command=submit)
choosefilebutton.pack()

root.mainloop()

它制作了一个二维码,但是当我扫描二维码时,结果是:

<_io.TextIOWrapper name='/Users/charliezhang/Desktop/hello.png' mode='r' encoding='UTF-8'>

我是 Python 新手,还不太了解所有内容 有人可以帮忙吗?

【问题讨论】:

  • 您实际上从未在文件上调用.read() 来获取其内容;你用文件对象本身制作了你的二维码。

标签: python tkinter python-imaging-library qr-code


【解决方案1】:

您只能获得带有askopenfile 的文件路径和名称数据。 应该是这样的:

f = open(file.name)
qr = qrcode.make(f.read())
f.close()

【讨论】:

  • 以上是对的,但你可以更简单地调用file.read()。或者,通过错误检查, (file.read() if file else "")
【解决方案2】:

在 Py 3.8.10 中,以下工作:

def submit():
    if file:
        qr = qrcode.make(file.read())
        qr.save('qrcode.png')

这里,从filedialog.askopenfile() 返回的file 不是字符串,而是类似文件的对象。因此,添加 .read() 会从文件中提取数据。 filedialog.askopenfilename() 方法返回一个字符串,它是文件名。

我还添加了文件检查,因为如果用户从“打开文件”对话框中点击“取消”按钮,file 将设置为“无”。因此,执行此检查有助于防止用户在之后点击提交按钮时再次出现错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 2022-11-22
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    相关资源
    最近更新 更多