Image search browser with Tkinter - python

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.

Related

Show results of Jupyterlab on Tkinter UI

I am currently working on building an UI to show the images in my JupyterLab to my Tkinter UI, that is running on a same script. In my script, I hope that after entering the values in Tkinter, it will take in the input and run again, and show the image on Tkinter UI again, so that I can do try and error. Can anyone guide me or give me a little tips to know where to find the answer and how to work on it?
from tk import *
from tkinter import ttk
from PIL import ImageTk, Image
import tkinter as tk
import os
window = tk.Tk()
def show_result(a,b,c,d):
#display the image result
#run the again to test the result
x1 = tk.IntVar()
x2 = tk.IntVar()
y1 = tk.IntVar()
y2 = tk.IntVar()
# set textbox to capture variables
x1_value = ttk.Entry(textvariable=x1).place(x=50, y=50)
x2_value = ttk.Entry(textvariable=x2).place(x=50, y=100)
y1_value = ttk.Entry(textvariable=y1).place(x=50, y=150)
y2_value = ttk.Entry(textvariable=y2).place(x=50, y=200)
display_button = ttk.Button(text="Run", command= lambda: show_result(x1.get(),x2.get(),y1.get(),y2.get())).place(x=50, y=300)
window.geometry("900x750")
window.mainloop( )
plt.figure(figsize = (50,8))
plt.imshow(crop_img, cmap='gray')
fig1 = plt.gcf()
fig1.savefig('crop_img.png', dpi=100)
open_img()
# Open img to show on tkinter
def open_img():
x = 'crop_img.png'
img = Image.open(x)
left=2000
top=0
right=3000
bottom=800
img = img.crop((left, top, right, bottom))
img = img.resize((800, 600), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
panel = Label(window, image=img)
panel.image = img
panel.place(x=200, y=0)

Tkinter Overlapping Label Text

I have just started utilizing Python's tkinter module to create some basic GUIs. In the GUI shown below, the user is prompted to upload the cafe image and subsequent cafe name will appear. However, I have not found a convenient way to clear the cafe label text for when the user upload another cafe image and classify again. I have the full code attached below.
import numpy as np
import cv2
import tkinter as tk
from tkinter import filedialog
from tkinter import *
from PIL import ImageTk, Image
from h5py import File
def upload():
global img
global filename
f_types = [('Png files', '*.png')]
filename = filedialog.askopenfilename(filetype=f_types)
img = ImageTk.PhotoImage(file = filename)
e1 = tk.Label(window)
e1.place(x=50, y=150)
e1['image'] = img
window.configure(background = '#CDCDCD')
show_classify_button()
def show_classify_button():
classify_btn = tk.Button(window, text='Classify Image', command=classification)
classify_btn.place(x=250, y=400)
classify_btn.configure(background = '#364156', foreground = 'white', font=('cambria', 15, 'bold') )
def classification():
matrix = []
image = cv2.imread(filename, 0)
array = np.array(image)
flatten_array = array.flatten()
matrix.append(flatten_array)
X = pca.transform(matrix)
pred = clf.predict(X)
if pred == 0:
Label(window, text='Casa De Cafe', font='Cambria 20 bold', background = '#CDCDCD', foreground = '#364156').place(x=170, y=300)
elif pred == 1:
Label(window, text='Coffeology', font='Cambria 20 bold', background = '#CDCDCD', foreground = '#364156').place(x=170, y=300)
else:
Label(window, text='Mori Cafe', font='Cambria 20 bold', background = '#CDCDCD', foreground = '#364156').place(x=170, y=300)
def main_account_screen():
global window
window = Tk()
window.title('Cafe Recognition System')
window.geometry('500x500')
window.configure(background = '#CDCDCD')
Label(window, text='Cafe Recognition System', font='Cambria 20 bold', background = '#CDCDCD', foreground = '#364156').place(x=110, y=50)
button = tk.Button(window, text='Upload', command=upload)
button.place(x=130, y=400)
button.configure(background = '#364156', foreground = 'white', font=('cambria', 15, 'bold') )
window.mainloop()
main_account_screen()

Convert multiple images to pdf

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

changing extensions of all images in a folder with tkinter

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.

Using Tkinter, how can I post the same image twice

import urllib, io
from Tkinter import *
from PIL import Image, ImageTk
from bs4 import BeautifulSoup
import Tkinter as tk
root = Tk()
root.geometry("1000x800+20+20")
im=[]
t1=[]
z1=[]
x=var=0
def Search():
global t1
global var
var = IntVar()
show = "http://blog.acorn-is.com/wp-content/uploads/apple-full2.jpg" #random google image
fd = urllib.urlopen(show)
imgFile = io.BytesIO(fd.read())
im.append (ImageTk.PhotoImage(Image.open(imgFile)))
image = Label(root, image = im[0])
t1.append(image)
z1.append(image)
#both t1 and z1 should contain the image..
r1 = Checkbutton(root, variable=var, command=Queue)
r1.place(bordermode=INSIDE, x=0, y=90)
def Queue():
if (var.get() == 1):
z1[0].place(bordermode=INSIDE, x=0, y=300) #x=0
t1[0].place(bordermode=INSIDE, x=550, y=300) #x=550
tx1 = StringVar()
b1 = Button(root, text="Search", command=Search, width="20")
b1.grid(row=0, column=0)
root.mainloop()
example code above. you'll notice in the Search function, that both t1 and z1 are appending the image to their own list but when i "place" z1 and t1, the image shows only once - only the second image shows. how can i get it to display the same image twice?
See the changes below. This will make it work !
import urllib, io
from Tkinter import *
from PIL import Image, ImageTk
from bs4 import BeautifulSoup
import Tkinter as tk
root = Tk()
root.geometry("1000x800+20+20")
im=[]
t1=[]
z1=[]
x=var=0
def Search():
global t1
global var
var = IntVar()
show = "http://blog.acorn-is.com/wp-content/uploads/apple-full2.jpg" #random google image
fd = urllib.urlopen(show)
imgFile = io.BytesIO(fd.read())
im.append (ImageTk.PhotoImage(Image.open(imgFile)))
image = Label(root, image = im[0])
t1.append(image)
# New added line
image = Label(root, image = im[0])
z1.append(image)
#both t1 and z1 should contain the image..
r1 = Checkbutton(root, variable=var, command=Queue)
r1.place(bordermode=INSIDE, x=0, y=90)
def Queue():
if (var.get() == 1):
z1[0].place(bordermode=INSIDE, x=0, y=300) #x=0
t1[0].place(bordermode=INSIDE, x=550, y=300) #x=550
tx1 = StringVar()
b1 = Button(root, text="Search", command=Search, width="20")
b1.grid(row=0, column=0)
root.mainloop()

Categories

Resources