I wanted to create a pdf converter app with python which converts images to pdf.
This is my code but it is only converting one image into pdf I tried many ways to fix it but none of them worked can anyone please help me because I want to convert multiple images into pdf but it is not working besides using for loop. I tried img2pdf but it giving alpha channel error and I am not able to solve that.
import PIL.Image
from tkinter import *
from tkinter import filedialog as fd
import PyPDF2
import img2pdf
from tkinter import ttk
root = Tk()
root.geometry('500x500')
root.resizable(0, 0)
filename = StringVar()
entry = Entry(root, width=50, textvariable=filename).place(x=115, y=250)
def Select_images():
global files
files = fd.askopenfilenames()
def select_dir():
global dir_name
dir_name = fd.askdirectory()
def submit():
global file_name
file_name = filename.get()
def create_pdf():
myfile=open(f'{dir_name}/{file_name}.pdf', 'wb+')
for image in files:
img=PIL.Image.open(image).convert('RGBA')
im1=img.convert('RGB')
im1.save(r'{}\{}.pdf'.format(dir_name,file_name))
myfile.close()
button = Button(root, text='Sumbit PDF Name', command=submit).place(x=200, y=300)
label = Label(root, text='Write PDF Name').place(x=210, y=215)
button1 = Button(root, text='Create File', command=create_pdf).place(x=215, y=335)
button2 = Button(root, text='Select Directory To Save File',command=select_dir).place(x=200, y=50)
button3 = Button(root, text='select Images', command=Select_images).place(x=235, y=100)
root.mainloop()
See if this helps you:
from tkinter import Tk, messagebox as mb, filedialog as fd
from tkinter.constants import DISABLED, NORMAL
from tkinter.ttk import Button, Label
from PIL import Image
import os
root = Tk()
root.title("Image to PDF converter")
root.geometry("500x500")
imglist = [] # For creating a list of images
fimgl = [] # List for storing multiple image names
png = True # If the image chosen is a .png file
def askfile():
global files, fimg, order, imglist, tm, png
files = fd.askopenfilenames(title="Choose images", filetypes=(("PNGs", "*.png"), ("JPGs", "*.jpg"), ("All Files", "*.*")))
for i in files:
fimgl.append(i)
if files:
for j in fimgl:
if j.endswith(".png"): # If the image is a PNG:
png = True
fnl = Label(root, text=j)
fnl.pack()
img = Image.open(j)
fimg = img.convert('RGB')
imglist.append(fimg)
p.config(state=NORMAL)
def convert_pdf():
global png
try:
if png:
imglist.pop()
saveloc = fd.asksaveasfilename(title="Save the PDF file")
if saveloc:
if saveloc.endswith(".pdf"):
pass
else:
saveloc = saveloc + ".pdf"
if os.path.exists(saveloc):
yn = mb.askyesno("Confirm Save As", f"{os.path.basename(saveloc)} already exists.\nDo you want to replace it?")
if yn:
os.remove(saveloc)
else:
convert_pdf()
fimg.save(saveloc, save_all=True, append_images=imglist)
mb.showinfo("Done!", "PDF file saved! Click 'OK' to open it")
os.startfile(saveloc)
root.quit()
except Exception as err:
mb.showerror("Error", err)
root.quit()
cb = Button(root, text="Add Files", command=askfile)
cb.pack(pady=20)
p = Button(root, text="Convert", command=convert_pdf, state=DISABLED)
p.pack(pady=20)
root.mainloop()
Related
I have made a pdf viewer using tkinter. I am wondering if I can let the pdf file 'pop out' using Toplevel() function. I tried to use lambda to try to incorporate the Toplevel() when using the button but the pop out window did not reflect anything. Here is the code I made:
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from tkPDFViewer import tkPDFViewer as pdf
import os
#make tk case
root = Tk()
root.geometry("1000x700+200+100")
root.title("PDF Viewer")
root.configure(bg="light blue")
#view frame
view_frame=Frame(root, bg="light blue", bd=5, width=400)
view_frame.pack(side=LEFT)
#to generate pop up window to view PDFs
def popup(filename):
win=Toplevel()
win.geometry("100x80")
win.title(filename)
v2=None
file = ''
#search for files
def viewpdf():
#make v2 global
global v2
filename=filedialog.askopenfilename(initialdir=os.getcwd(),
title="Select PDF File",
filetype=(("PDF File", ".pdf"),
("PDF File", ".PDF"),
("All File",".txt")))
if filename:
global file
file=filename
#destroy old file if it exists
if v2:
v2.destroy()
#create new pdf images
v1=pdf.ShowPdf()
#clear stored images
v1.img_object_li.clear()
#store new images
v2=v1.pdf_view(view_frame, pdf_location=open(filename,"r"),height=50, width=80)
v2.pack(pady=(0,0))
#set buttons
view_button=Button(view_frame, text='SEARCH FOR FILES', command=lambda: [viewpdf(), popup(file)], width=50, bd=5)
view_button.pack()
root.mainloop()
Update: I have tried adding tkinter.TopLevel() inside the def viewpdf() and it worked! I have deleted the def popup() as well.
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from tkPDFViewer import tkPDFViewer as pdf
import os
#make tk case
root = Tk()
root.geometry("1000x700+200+100")
root.title("PDF Viewer")
root.configure(bg="light blue")
#view frame
view_frame=Frame(root, bg="light blue", bd=5, width=400)
view_frame.pack(side=LEFT)
v2 = None
#search for files
def viewpdf():
#make v2 global
global v2
filename=filedialog.askopenfilename(initialdir=os.getcwd(),
title="Select PDF File",
filetype=(("PDF File", ".pdf"),
("PDF File", ".PDF"),
("All File",".txt")))
if filename:
#destroy old file if it exists
if v2:
v2.destroy()
#create new pdf images
v1=pdf.ShowPdf()
#clear stored images
v1.img_object_li.clear()
#set a new pop out window
newWindow=tkinter.Toplevel(view_frame)
#store new images
v2=v1.pdf_view(newWindow, pdf_location=filename, height=50, width=80)
v2.pack(pady=(0,0))
Hi I'd like to have in my tkinter GUI a progress bar that gives visual cue about the status of the loading of a file. This is my code, but when I launch it the app just get stuck and does not work (I have to close it by force).
def start():
file = filedialog.askopenfilename(filetypes =(("Text File", "*.txt"),("All Files","*.*")), title = "Select")
filesize = os.path.getsize(file)
with open(file, "r", encoding='utf-8') as f:
for i in range(os.path.getsize(file)):
progressbar["value"] = 5
progressbar["maximum"] = filesize
label.config(text=str(progressbar["value"]) + "%")
root.update_idletasks()
time.sleep(1)
label = ttk.Label(root, text="00%")
label.pack()
button_prg = Button(root, text="progress", command=start)
button_prg.pack()
progressbar = ttk.Progressbar(root, orient="horizontal", length=100, mode='determinate')
progressbar.pack()
Also is there a way to resize the height of the bar? since I'd like to put it in the status bar at the bottom of my frame. Thank you all!
well what you want, i didn't understand clearly..
but here's what you shall have:
import time
import os
from tkinter import * #importing * is a very bad habit!
from tkinter import ttk
from tkinter import filedialog
def start():
file = filedialog.askopenfilename(filetypes =(("Text File", "*.txt"),("All Files","*.*")), title = "Select")
filesize = os.path.getsize(file)
with open(file, "r", encoding='utf-8') as f:
for i in range(os.path.getsize(file)):
progressbar["value"] = progressbar["value"]+1
progressbar["maximum"] = filesize
label.config(text=str(int(progressbar["value"]/os.path.getsize(file)*100)) + "%")
root.update_idletasks()
#time.sleep(1)
root = Tk()
label = ttk.Label(root, text="00%")
label.pack()
button_prg = Button(root, text="progress", command=start)
button_prg.pack()
progressbar = ttk.Progressbar(root, orient="horizontal", length=100, mode='determinate')
progressbar.pack()
root.mainloop()
btw, there's a limit in the file size.. that is 400kb.. i am just unable to load any of my files larger than 400kb in size!
I want to convert the image formats of all images in a folder using tkinter. all extensions I want in a combobox but I don't know why this code doesn't work .no error is displayed.
from tkinter import filedialog, StringVar
from tkinter import ttk
root=tkinter.Tk()
root.geometry("800x600")
#defining functions
def get_folder():
global folder_path
folder_path = filedialog.askdirectory(initialdir='./', title="Select Folder")
print(folder_path)
def get_extension():
change_to = com.get()
change_from = "py"
files=os.listdir(folder_path)
for file in files:
if (".%s"%change_from) in file:
newfile=file.replace((".%s"%change_from),".%s"%change_to)
os.rename((folder_path+'/'+file),(folder_path+'/'+newfile))
#defining widgets for frames
folder_label = tkinter.Label(from_frame)
browse_button = tkinter.Button(from_frame, text="Browse", command=get_folder)
change_button = tkinter.Button(button_frame, text="Change Extension", command=get_extension)
change_button.pack()
#defining combobox
com = StringVar()
list_combo = ['.png','.jpg','.jpeg', '.svg', '.tif','.bmp','.gif','ppm']
combox = ttk.Combobox(root, width = 25, font = 'arial 19 bold', value = list_combo, state = 'r', textvariable = com)
combox.place(x= 190, y= 190)
combox.set('select type')
root.configure(bg = 'coral1')
root.mainloop()```
Is this what You want:
from tkinter import Tk, Button, Label, StringVar, Frame
from tkinter.ttk import Combobox
from tkinter.filedialog import askdirectory
import os
def convert_extensions():
path = dir_lbl.cget('text')
from_ = from_var.get()
to_ = to_var.get()
files_from = [f'{path}/{file}' for file in os.listdir(path) if file.split('.')[-1] == from_]
files_to = ['.'.join(file.split('.')[:-1]) + '.' + file.split('.')[-1].replace(from_, to_) for file in files_from]
for from_file, to_file in zip(files_from, files_to):
os.rename(from_file, to_file)
print(f'{"-" * 100}\n'
f'{"From:": <10} {from_file}\n'
f'{"To:": <10} {to_file}\n')
root = Tk()
root.geometry('500x200')
Button(root, text='Choose Directory', command=lambda: dir_lbl.config(text=askdirectory())).pack(pady=5)
dir_lbl = Label(root, text='')
dir_lbl.pack(pady=5)
options_frame = Frame(root)
options_frame.pack(pady=5)
from_var = StringVar(value='Convert from')
list_combo = ['png', 'jpg', 'jpeg', 'svg', 'tif', 'bmp', 'gif', 'ppm']
Combobox(options_frame, value=list_combo,
textvariable=from_var, state='r').pack(side='left', padx=5, pady=5)
to_var = StringVar(value='Convert to')
Combobox(options_frame, value=list_combo,
textvariable=to_var, state='r').pack(side='left', padx=5, pady=5)
Button(root, text='Convert', command=convert_extensions).pack(pady=5)
root.mainloop()
This however allows more control in that You can choose both the extension to convert and to which one convert.
This is pretty basic so if You have any questions, ask. I will probably add a detailed explanation later but for now this is all I can do. Oh and btw that three line print function is not necessary at all and it probably should be made to display that in tkinter window or sth but otherwise it can be removed.
I'm trying to do an image search engine with Tkinter. Basically a "Pokedex" that searches for images inside a specific folder on my computer associated with a specific name.Example of the image output
import tkinter as tk
from io import BytesIO
import matplotlib.pyplot as plt
import os
import glob
import natsort
from PIL import Image
from PIL import ImageTk
window = tk.Tk()
window.geometry("600x500")
window.title("CoreaninhaDex")
window.config(padx=10, pady=10)
title_label = tk.Label(window, text = 'CoreaninhaDex')
title_label.config(font=('Arial', 32))
title_label.pack(padx=10, pady=10)
target_image = tk.Label(window)
target_image.pack(padx=10, pady=10)
target_information = tk.Label(window)
target_information.config(font=("Arial", 20))
target_information.pack(padx=10, pady=10)
photos_names_list = ["target1","target2","target3","target4","target5"]
#FUNCTION
def showimage():
dir1 = r"C:\Users\path"
path1 = os.path.join(dir1, '*g')
files = glob.glob(path1)
files1 = natsort.natsorted(files, reverse=False)
for x in files1:
img = plt.imread(x)
image = Image.open(img)
imag = ImageTk.PhotoImage(image)
target_image.config(image=imag)
target_image.image = imag
label_id_name = tk.Label(window, text="ID or Name")
label_id_name.config(font=("Arial", 20))
label_id_name.pack(padx=10, pady=10)
text_id_name = tk.Text(window, height = 1)
text_id_name.config(font=("Arial", 20))
text_id_name.pack(padx=10, pady=10)
btn_load = tk.Button(window, text="Load target", command = showimage)
btn_load.config(font=("Arial", 20))
btn_load.pack(padx=10, pady=10)
window.mainloop()
The output generates a display. But I can't associate the image with any name or even upload the images.
I would like help to write a showimage () function that would do this.
I am experiencing some issues when displaying the location of the image selected. Is there a reason why it displays <_io.TextIOWrapper name =along with mode='r'encoding ='cp1252>? I just want it to display the location of the image along with the name of the image not those extra stuff. Is there something that I am doing that is causing this to occur? Please advise.
def button(self):
self.button = ttk.Button(self.labelFrame, text = "Upload Image", command = self.fileDialog)
self.button.grid(column = 1, row = 1)
def fileDialog(self):
self.filename = filedialog.askopenfile(initialdir = "/", title = "Select a File", filetype = (("jpeg", "*.jpg"), ("All files", "*.")))
self.label = ttk.Label(self.labelFrame, text = "")
self.label.grid(column = 1, row = 2)
self.label.configure(text = self.filename)
filedialog.askopenfile gives file object, not file name.
You have to display self.filename.name instead of self.filename
Full working example
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
file_object = filedialog.askopenfile(title="Select file")
print('file_object:', file_object)
print('file_object.name:', file_object.name)
#data = file_object.read()
label = tk.Label(root, text=file_object.name)
label.pack()
root.mainloop()
Or use askopenfilename instead of askopenfile and you get file name.
Full working example
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
filename = filedialog.askopenfilename(title="Select file")
print('filename:', filename)
#data = open(filename).read()
label = tk.Label(root, text=filename)
label.pack()
root.mainloop()