我已经在python中为tkinter GUI编写了一个函数,如下所示:
def mgpd():
answer = filedialog.askdirectory(parent=root,
initialdir=os.getcwd(),
title="Please select a folder:")
if len(answer) > 2:
with open("output.pdf", "wb") as f:
f.write(img2pdf.convert([i for i in os.listdir(answer) if i.endswith(".jpg")]))
else:
pass
t2.delete(0, 'end')
t2.insert('insert', 'task completed.')
现在,当我选择一个文件夹时,类型错误将显示为TypeError: a bytes-like object is required, not 'str'
。我猜是endswith
周围的问题。
答案 0 :(得分:0)
Python抱怨类字节对象通常是因为您要更改的任何字符串都已编码。尝试使用if i.endswith(".jpg")]
代替if i.decode().endswith(".jpg")]
。
答案 1 :(得分:0)
最后,这就是答案:
def mgpd():
image_files = []
answer = filedialog.askdirectory(parent=root,
initialdir=os.getcwd(),
title="Please select a folder:")
if len(answer) > 2:
for file in os.listdir(answer):
if file.endswith(".jpg"):
image_files.append(os.path.join(answer, file))
else:
pass
outfile = os.path.join(answer, 'output.pdf')
pdf_bytes = img2pdf.convert(image_files)
file = open(outfile, "wb")
file.write(pdf_bytes)
t2.delete(0, 'end')
t2.insert('insert', 'task completed.')