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)
Related
I'm working on a python project that takes an image that the user selects and removes a certain color from it, I'm trying to display the selected image along with a button that takes you to the selection menu on the file explorer on the user's computer, the button works just fine, but the image is not being displayed at all. any help would be appreciated.
the code:
#import
from PIL import Image, ImageTk
from fileinput import filename
import tkinter as tk
from tkinter import filedialog
from tkinter import *
root = Tk()
root.geometry("750x500")
root.title("Shibly Letter Head")
canvas = Canvas(root, width = 500, height = 500)
canvas.pack()
#uploaded info
def UploadAction(event=None):
from PIL import Image
filename = filedialog.askopenfilename()
print('Selected:', filename)
img = Image.open(filename)
img.show()
image_data = img.load()
height,width = img.size
for loop1 in range(height):
for loop2 in range(width):
r,g,b = image_data[loop1,loop2]
image_data[loop1,loop2] = 0,g,b
img.save('changed.jpeg')
#display image
canvas.create_image(10,
10,
anchor=NW,
image= filename
)
#button
button = tk.Button(root, text='Open', height=5, width=45, command=UploadAction)
button.place(x=220, y=419)
root.mainloop()
PS, apologies if this is a dumb question but I'm still a beginner and couldn't fix this problem myself.
I am trying to run following code, which run successfully... but when I am trying to import matplotlib it give error ----> _tkinter.TclError: image "pyimage1" doesn't exist while using PyCharm, but with python IDLE it works without error.
import cv2
from tkinter import *
from PIL import Image, ImageTk
import datetime
import openpyxl
#from matplotlib import pyplot as plt
def show_frames():
im = cap.read()[1]
Image1= cv2.cvtColor(im,cv2.COLOR_BGR2RGB)
img = Image.fromarray(Image1)
imgtk = ImageTk.PhotoImage(image = img)
label.imgtk = imgtk
label.configure(image=imgtk)
label.after(20, show_frames)
def capture():
I = cap.read()[1]
save_name = str(datetime.datetime.now().today()).replace(":", " ") + ".jpg"
cv2.imwrite(save_name, I)
#here creating window and GUI
win = Tk()
win.geometry("1200x650")
win.title('Portable Optical Spectrometer')
L2 = Label(win,text = " Camera ",font=("times new roman",20,"bold"),bg="white",fg="red").grid(row=0, column=0)
L2 = Label(win,text = " Spectrum Graph ",font=("times new roman",20,"bold"),bg="white",fg="red").grid(row=0, column=2)
label =Label(win)
label.grid(row=1, column=0)
cap = cv2.VideoCapture(0)
show_frames()
B1 = Button(win,text="Capture",font=("Times new roman",20,"bold"),bg="white",fg="red",command=capture()).grid(row=3, column=0, )
B1 = Button(win,text="Analysis",font=("Times new roman",20,"bold"),bg="white",fg="red",).grid(row=4, column=0)
L1 = Label(win,text = "Detected Material is: ",font=("times new roman",20,"bold"),bg="white",fg="red").grid(row=4, column=1)
Output = Text(win, height = 3,width = 25,bg = "light cyan").grid(row=4, column=2)
win.mainloop()
cap.release()
can someone suggest how to solve this error
Yeah, the PhotoImage is poorly documented, but it seems that if you have more than one Tkinter root then you need to specify which root that the PhotoImage should use — with the "master" argument. This applies to both the basic Tkinter PhotoImage and Pillow's ImageTk wrapper. Matplotlib usually uses Tk as its backend so that will usually invoke the problem. IDLE also uses Tk so it's anybody's guess what that combination would do.
See the following example. If the "master=" argument is removed from either of the two PhotoImage creation lines below then it errors out.
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
import tkinter as tk
root = tk.Tk()
photimg = tk.PhotoImage(width=100,height=100, master=root)
tk.Label(root, image=photimg).pack()
from PIL import Image, ImageTk
pilimg = Image.new(mode="RGB", size=(200, 200))
imgtk = ImageTk.PhotoImage(image=pilimg, master=root)
tk.Label(root, image=imgtk).pack()
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 trying to code a game for my school assignment. In this game, I wanted to have a mute button so I have made a button on top of a label frame and place it in a label. I don't know what is wrong with it but the image does not show up. I have tried to create a local copy by assigning it to a temp variable and yet it still doesn't show up. Here's my code:
from tkinter import ttk
from PIL import Image, ImageTk
root = Tk()
topFrame =Frame(root, width=500, height=50,)
topFrame.grid(row=0, column= 0)
btnframe = LabelFrame(topFrame, width = 20, height = 20)
btnframe.place(x = 450, y= 5 )
mute_image = Image.open("pygame/mute.png")
mute_image = mute_image.resize((50,50), Image.ANTIALIAS)
mute_icon = ImageTk.PhotoImage(mute_image)
mute_button = Button( btnframe, width = 50, height = 50, command = Mute, image = mute_icon)
mute_button.image = mute_icon
mute_button.pack()
root.mainloop()
Please go easy on me, this is my first time coding a game ever:)) Thanks in advance:))
Are you getting any error messages. I slightly modified your code and it complained abuot the button callback function was not defined. After I added that it all seems to work.
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
topFrame =Frame(root, width=500, height=50,)
topFrame.grid(row=0, column= 0)
btnframe = LabelFrame(topFrame, width = 20, height = 20)
btnframe.place(x = 450, y= 5 )
def Mute():
pass
mute_image = Image.open("images/beer.png")
mute_image = mute_image.resize((50,50), Image.ANTIALIAS)
mute_icon = ImageTk.PhotoImage(mute_image)
mute_button = Button(btnframe, width=50, height=50,
command=Mute, image=mute_icon)
mute_button.image = mute_icon
mute_button.pack()
root.mainloop()
I'm trying to create a program using Tkinter that displays a thumbnail from several different directories in on window. So far I have this:
import Tkinter as tk
from PIL import Image, ImageTk
import Image, os
root = tk.Tk()
root.title('Shot Viewer')
w, h, x, y = 1000, 1000, 0, 0
root.geometry("%dx%d+%d+%d" % (w, h, x, y))
#quit
def quit(root):
root.quit()
root.destroy()
path = "/media/Expansion Drive/Heros Mission 3/Scenes/Scene 1-3/Shots/"
labels = []
for files in os.listdir(path):
number = files.split("_")[1]
filed = "/media/Expansion Drive/Heros Mission 3/Scenes/Scene 1-3/Shots/Shot_{} /Frames/Shot_{}_000000.png".format(number, number)
if os.path.lexists(filed) == 'False':
pass
else:
im = Image.open(imageFile)
im.thumbnail((96, 170), Image.ANTIALIAS)
image = ImageTk.PhotoImage(im)
label = tk.Label(root, image=image, name=number)
labels.append(label)
print labels
for label in labels:
panel = label.grid()
panel2.grid(row=2, column=1)
button2 = tk.Button(panel2, text='Quit', command=lambda root=root:quit(root))
button2.grid(row=1, column=1, sticky='NW')
root.mainloop()
However this is not working, does anyone have any suggestions?
Thanks
Tom
Use the glob module to help find the relevant files.
As for images failing to appear:
import Tkinter as tk
from PIL import Image, ImageTk
import glob
root = tk.Tk()
labels = []
for jpeg in glob.glob("C:/Users/Public/Pictures/Sample Pictures/*.jpg")[:5]:
im = Image.open(jpeg)
im.thumbnail((96, 170), Image.ANTIALIAS)
photo = ImageTk.PhotoImage(im)
label = tk.Label(root, image=photo)
label.pack()
label.img = photo # *
# * Each time thru the loop, the name 'photo' has a different
# photoimage assigned to it.
# This means that you need to create a separate, 'longer-lived'
# reference to each photoimage in order to prevent it from
# being garbage collected.
# Note that simply passing a photoimage to a Tkinter widget
# is not enough to keep that photoimage alive.
labels.append(label)
root.mainloop()
I do not think you are handling it correctly where you say panels = label.grid(). Instead, try to just do label.grid so it is not an assignment operator but an action.