Charlie Zhang
Charlie Zhang

Reputation: 65

I tried to make a QRcode from the user's input file with Python but its not working

Here is my code:

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()

It makes a QR code but when I scan the QR code the result is:

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

I'm new to Python and don't understand everything too well yet Can someone please help?

Upvotes: 0

Views: 286

Answers (2)

GaryMBloom
GaryMBloom

Reputation: 5682

In Py 3.8.10, the following works:

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

Here, file returned from filedialog.askopenfile() is not a string but a file-like object. So, adding the .read() pulls the data from the file. The filedialog.askopenfilename() method returns a string which is the name of the file.

I also add a check for file, since if the user hits the Cancel button from the Open File dialog, file gets set to None. So doing this check helps prevent another error when the user hits the Submit button afterwards.

Upvotes: 1

Just me
Just me

Reputation: 71

You only get a file path and name data with askopenfile. Should be something like:

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

Upvotes: 1

Related Questions