How to display adjusted PIL images in Tkinter? [duplicate] - python

This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Tkinter PIL image not displaying inside of a function
(1 answer)
Closed 1 year ago.
I am attempting to make a simple Tkinter app that displays an image on screen, and that reduces the brightness of the image when you click:
from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk, ImageEnhance
def update_image(img):
enhancer = ImageEnhance.Brightness(img)
temp_img = enhancer.enhance(0.5)
temp_tkimg = ImageTk.PhotoImage(temp_img)
panel.configure(image=temp_tkimg)
root = Tk()
img = Image.open('img.png')
tkimg = ImageTk.PhotoImage(img)
panel = ttk.Label(root, image=tkimg)
panel.pack(side="bottom", fill="both", expand="yes")
panel.bind('<1>', lambda e: update_image(img))
root.mainloop()
This correctly displays the initial image, but after clicking, instead of rendering the new image it just disappears. I've tried saving the temp_tkimg as a new png and reopening it the same way I do with the initial image but this doesn't work either:
def update_image(img):
enhancer = ImageEnhance.Brightness(img)
temp_img = enhancer.enhance(0.5)
temp_img.save('temp.png')
temp_tkimg = PhotoImage(file='temp.png')
panel.configure(image=temp_tkimg)
I feel like this is a pretty simple concept so not sure what I'm missing.
Cheers.

Related

Tkinter:Cant place image which imported from Pixmap inside text widget using button

So i am using python 3 and got confused why the image doesnt show up in text widget after excuted the following code:
from tkinter import *
import fitz
root=Tk()
filenew=fitz.open(r'C:\Users\azoka\Desktop\Python\b.pdf')
text_1=Text(root,width=100,height=100,bg='gray').pack(side=LEFT,expand=FALSE)
def Show():
pix =filenew.getPagePixmap(0) # 0 is page number
pix1=fitz.Pixmap(pix,0)
img =pix1.getImageData("ppm")
timg=PhotoImage(data=img)
frame=[]
frame.append(timg)
text_1.image_create(END,image=timg)
Shower=Button(win1,text='show',bg='navy',fg='light cyan',width=5,height=1,command=Show)
Shower.place(x=1000,y=360)
root.mainloop()
The image just dont show up after clicked the button but it doesnt show any code error,I am new to python
and cant figure out. I want my img be shown without altering the Show()function.
-Appreciate for helpful answers!-
I tried to use the from previous code but not works
I made some fix with last version today, see fix bellow with simplifications
from tkinter import *
from PIL import Image, ImageTk
import fitz
root = Tk()
file = "yourfile.pdf"
doc = fitz.open(file)
page = doc.load_page(0) # loads page number 'pno' of the document (0-based)
pix = page.get_pixmap()
mode = "RGBA" if pix.alpha else "RGB"
img = Image.frombytes(mode, [pix.width, pix.height], pix.samples)
frame_image = ImageTk.PhotoImage(img)
label = Label(root, bg='gray')
label.pack(side=LEFT)
label.config(image=frame_image)
label.image = frame_image
root.mainloop()
requirements to use "PyMuPDF-1.21.1"
pip install --upgrade pymupdf
see more: https://pymupdf.readthedocs.io/

How to display an image (on a canvas) selected via filedialog?

I started a project a few days ago but unfortunately I'm stuck. I would like to make an image editor (a very simple one ;D) where a choose an image by using the filedialog then I would have the possibilty to make few modifications like rotations. My problem is that I can choose the image but once I did, I can't show the image on the canvas.
It says : "name 'image' is not define"
I think my problem is that the program want to show the image on the canvas but I haven't selected it yet.
from tkinter import *
from PIL import Image, ImageTk
from tkinter import filedialog
root = Tk()
#function to select my image by using the filedialog
def select_image():
file_path = filedialog.askopenfilename()
image = Image.open(file_path)
#button to press to open filedialog
select = Button(root, text="select an image", command=select_image)
select.pack()
#the canvas where the image will be display
canvas = Canvas(root, width= 100, height=100, bg="grey")
canvas.pack()
image_tk = ImageTk.PhotoImage(image)
canvas.create_image(0,0, image= image_tk)
root.mainloop()
It is possible to create an image object before you have an image file to display, but not in the way you're doing it. You simply need to create an empty image object and keep track of the image object id, and then reconfigure that object inside of select_image.
For example, don't define image_tk in the main program. Change the line that creates the image item on the canvas to this:
image_id = canvas.create_image(0,0, anchor="nw")
(note: without the anchor option, the center of the image will be at 0,0. I'm guessing you want the upper-left corner of the image to be at 0,0).
Next, in select_image is where you do all of the work of getting the image, saving a reference to it (to avoid it being deleted when the function returns), and showing it in the canvas. It would look something like this:
def select_image():
# ask the user for the filename
file_path = filedialog.askopenfilename()
# only show the image if they chose something
if file_path:
# open the file
image = Image.open(file_path)
# create the image object, and save it so that it
# won't get deleted by the garbage collector
canvas.image_tk = ImageTk.PhotoImage(image)
# configure the canvas item to use this image
canvas.itemconfigure(image_id, image=canvas.image_tk)
You’ve got a couple of problems here:
You are never calling your function! Your code ignores
select_image() after it is defined
The variable image is only defined inside your (uncalled) function, so when you try to use it via ImageTk.PhotoImage(), it is
undefined.
Try returning the image object this way:
from tkinter import *
from PIL import Image, ImageTk
from tkinter import filedialog
root = Tk()
#function to select my image by using the filedialog
def select_image():
file_path = filedialog.askopenfilename()
return Image.open(file_path)
#button to press to open filedialog
select = Button(root, text="select an image", command=select_image)
select.pack()
#the canvas where the image will be display
canvas = Canvas(root, width= 100, height=100, bg="grey")
canvas.pack()
image_tk = ImageTk.PhotoImage(select_image())
canvas.create_image(0,0, image= image_tk)
root.mainloop()
Note that you are not checking for errors or cancellation in your select_image() function. You’d be better off handling cancel or error inside the function too

Button displaying white canvas instead of image [duplicate]

This question already has answers here:
Tkinter Label does not show Image
(3 answers)
Closed 7 years ago.
I'm trying to create an image, but it's not working and I'm not sure what I'm doing wrong. All I get when I click the button that should display the image is the white canvas, without the image. How do I get it to display?
def show_original(self):
from os.path import exists
from PIL import Image, ImageTk
if not os.path.exists(self.wdg_orig_file_name_.get()):
tkMessageBox.showinfo('Load','File does not exist:' + self.wdg_orig_file_name_.get())
return
self.orig_image_=Image.open(str_orig_file_name)
canvas = self.gui_.ca(500,500,bg='white')
im_TK = ImageTk.PhotoImage(self.orig_image_)
canvas.create_image(250,250,image=im_TK)
canvas.pack()
pass
self.wdg_orig_file_name_.get() in the main loop is:
self.wdg_orig_file_name_ = self.gui_.en(text='boat.png')
The global str_orig_file_name is assigned in pick_file():
def pick_file(self):
'''Opens a file dialog and sets its result to the filename entry'''
global str_orig_file_name
str_orig_file_name = tkFileDialog.askopenfilename()
if str_orig_file_name:
self.wdg_orig_file_name_.delete(0, END)
self.wdg_orig_file_name_.insert(0, str_orig_file_name)
#We got a new image to process. Forget the previous results.
self.orig_image_ = None
self.preview_image_ = None
Have you tried easygui?
#!/usr/bin/python
from easygui import *
image = "img.jpg"
msg = "Do you like this picture?"
choices = ["Yes","No","No opinion"]
reply=buttonbox(msg,image=image,choices=choices)
Very easy.
http://www.ferg.org/easygui/tutorial.html
I'm sorry. I though the OP was looking for a way to display an image and now I see the image is supposed to be on the button. Well I tried this and it works just fine with .gif and .png. However .jpg gives an error: "_tkinter.TclError: couldn't recognize data in image file "img.jpg"".
#!/usr/bin/python
from Tkinter import *
root=Tk()
b=Button(root,justify = LEFT)
photo=PhotoImage(file="img.png")
b.config(image=photo,width="100",height="100")
b.pack(side=LEFT)
root.mainloop()

Read an image with OpenCV and display it with Tkinter

I have a very simple program on Ubuntu 14.04 LTS to read and display an image using OpenCV:
import cv2 #import OpenCV
img = cv2.imread('picture.jpg') #read a picture using OpenCV
cv2.imshow('image',img) # Display the picture
cv2.waitKey(0) # wait for closing
cv2.destroyAllWindows() # Ok, destroy the window
My problem:
How can I keep reading the picture in OpenCV but display it using Tkinter ?
I ask this because I want to make an interface for my program but OpenCV is not able to do it so I need Tkinter for this. However, all the image processing I must do it on the background using OpenCV. Only displaying the results must be done using Tkinter.
EDIT:
From the answer above, I change the line:
im = Image.open('slice001.hrs').convert2byte()
To:
im=cv2.imread() # (I imported cv2)
But I got an error.
I would appreciate any hints.
You might want to take a look at this one. Here is something works for me:
import numpy as np
import cv2
import Tkinter
from PIL import Image, ImageTk
# Load an color image
img = cv2.imread('img.png')
#Rearrang the color channel
b,g,r = cv2.split(img)
img = cv2.merge((r,g,b))
# A root window for displaying objects
root = Tkinter.Tk()
# Convert the Image object into a TkPhoto object
im = Image.fromarray(img)
imgtk = ImageTk.PhotoImage(image=im)
# Put it in the display window
Tkinter.Label(root, image=imgtk).pack()
root.mainloop() # Start the GUI
For Python3 I had to modify #Ha Dang answer:
from tkinter import *
from PIL import Image, ImageTk
import cv2
import numpy as np
image_name = 'bla.jpg'
image = cv2.imread(image_name)
#Rearrang the color channel
b,g,r = cv2.split(image)
img = cv2.merge((r,g,b))
# A root window for displaying objects
root = Tk()
# Convert the Image object into a TkPhoto object
im = Image.fromarray(img)
imgtk = ImageTk.PhotoImage(image=im)
# Put it in the display window
Label(root, image=imgtk).pack()
root.mainloop() # Start the GUI
Requirements were:
pip3
numpy==1.13.1
opencv-python==3.3.0.9
Pillow==4.2.1
brew
python3
tcl-tk
For me both answers above did not work but were close. The following code did the trick for me (I also want to use place instead of pack):
from PIL import ImageTk, Image
image = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB)
image = ImageTk.PhotoImage(image=Image.fromarray(image))
label_image = Label(self.detection, image=image)
label_image.image = image
label_image.place(x=0, y=0, anchor="w")

Adding image to Tkinter

I have added a image file to my code in tkinter but it basically fills my the whole frame so if its possible can you recommend a tutorial that shows or explains how to do this.... unless you can show me on here.
I havent added my full code but the code below should display a test image once you have it saved in the python directory.
I would like to create 'next' button which would open up a new frame with another image on it.
from Tkinter import *
root = Tk()
ButtonImage = PhotoImage(file='test.gif')
testButton = Button(root, image=ButtonImage)
testButton.pack()
root.mainloop()
You could try something like this:
from Tkinter import *
from glob import glob
class ImageFrame(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.images = glob("*.gif")
self.cur = 0
# label showing the image
self.image = PhotoImage()
imagelabel = Label(self, image=self.image)
imagelabel.grid(row=1, column=1)
# button cycling through the images
button = Button(self, text="NEXT", command=self.show_next)
button.grid(row=2, column=1)
# layout and show first image
self.grid()
self.show_next()
def show_next(self):
self.cur = (self.cur + 1) % len(self.images)
self.image.configure(file=self.images[self.cur])
ImageFrame().mainloop()
Some explanations:
glob is used to get a list of all files matching some pattern in the current directory
grid is a simple but quite flexible layout manager for Tkinter (see Tkinter reference)
the show_next method, which is bound to the button, cycles through the images and binds a new image to the PhotoImage using configure
The result is a simple frame showing a large image and a button, cycling though the gif images in the current directory.
There are numerous modules that would help you out with this. You can use the PIL module. Typically what I would do in a situation like yours is use the PIL module to load and paste the image onto the frame. This is how you do this.
from Tkinter import *
from PIL import Image, ImageTk
root = Tk()
Image = Image.open(path).resize((300, 300)), Image.ANTIALIAS
ButtonImage = ImageTk.PhotoImage(Image)
# If you are using image by itself. Without it being a button.
#Image_Label = Label(image = self.HomeImage, borderwidth=0, highlightthickness=0)
# Otherwise
testButton = Button(root, image=ButtonImage)
testButton.pack()
root.mainloop()
I believe that this would definitely help you with resizing the image and loading an image to the screen as a button. We used PIL to load the image onto the frame and resized the image. This is What you were also asking for earlier. I used the resize method on the Image.open() Function. This resizes the image to what you want. The standards are the actual sizes of that image.

Categories

Resources