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?
CodePudding user response:
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()
CodePudding user response:
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.