Can't get image to display in tkinter - python

I am trying to get an image to display in a tkinter canvas.
I know the Canvas works with shapes and text, but image isn't working.
I am using PIL ImageTK.PhotoImage, however it also doesn't work creating a Tkinter.PhotoImage using a '.ppm' image.
The 'png' image is stored in the same directory as the python file.
import tkinter as tk
from PIL import Image, ImageTk
class Window:
def __init__(self):
self.window = tk.Tk()
self.window.title("COMP")
self.window.geometry("1200x600")
topframe = tk.Frame(self.window, highlightbackground='black', highlightthickness=1)
topframe.pack(side='top')
self.noteview = NoteView(topframe, self.songString)
class NoteView:
def __init__(self, frame):
self.canvas = tk.Canvas(frame, width=60, height=200)
self.canvas.pack()
self.canvas.create_text(15, 190, text='hi')
im = Image.open('png.png')
self.image = ImageTk.PhotoImage(im)
self.canvas.create_image(20, 20, anchor='nw', image=self.image)
w = Window()
TypeError: 'PhotoImage' object is not callable

The proble is that the tkinter somehow bings the image to the window, not in your case. You should use self.canvas.image = ImageTk.PhotoImage(im) and self.canvas.create_image(20, 20, anchor='nw', image=self.canvas.image). Hope that's helpful!

Related

I am getting an AttributeError when I try to resize an image I have inserted to a Tkinter window

I am trying to resize an image I inserted in my Tkinter window, but keep receiving this error message: "AttributeError: 'PhotoImage' object has no attribute 'resize'"
This is my code to resize the image:
self.path = 'S:/Öffentliche Ordner/Logos/Core Solution/Logo/CoreSolution_Logo_RGB.jpg'
self.img = ImageTk.PhotoImage(Image.open(self.path))
self.resized = self.img.resize(50,50)
self.new_img = ImageTk.PhotoImage(self.resized)
self.label = Label(master, image = self.new_img)
self.label.pack()
self.Main = Frame(self.master)
How can I resolve this error? All help is welcomed and appreciated.
As in this tutorial, it looks like it is easier to import the file as an image. Then resize it, then convert it to PhotoImage. Can you give it a try ?
# Import the required libraries
from tkinter import *
from PIL import Image, ImageTk
# Create an instance of tkinter frame or window
win=Tk()
# Set the size of the tkinter window
win.geometry("700x350")
# Load the image
image=Image.open('download.png')
# Resize the image in the given (width, height)
img=image.resize((450, 350))
# Conver the image in TkImage
my_img=ImageTk.PhotoImage(img)
# Display the image with label
label=Label(win, image=my_img)
label.pack()
win.mainloop()
https://www.tutorialspoint.com/resizing-images-with-imagetk-photoimage-with-tkinter
As far as I can see, the Pillow Image.PhotoImage class is meant for displaying in tkinter but does not have all the methods of the tkinter.PhotoImage class.
Easiest is to resize the Pillow.Image before converting to Pillow Image.PhotoImage.
from tkinter import *
from PIL import Image, ImageTk
master = Tk()
path = 'images/cleese.png'
img = Image.open(path)
img.thumbnail((50,50)) # Resize Pillow Image
new_img = ImageTk.PhotoImage(img) # Convert
label = Label(master, image=new_img)
label.pack()
master.mainloop()
Try this. I did not test.
path = Image.open('S:/Öffentliche Ordner/Logos/Core Solution/Logo/CoreSolution_Logo_RGB.jpg'
self.resized = path.resize{(50,50),Image.ANTIALIAS)
self.img = ImageTk.PhotoImage(self.resized)
self.label = Label(master, image = self.new_img)
self.label.pack()
self.Main = Frame(self.master)

Tkinter/Python Canvas doesn't display image from OpenCV

I have class MainWindow for main window:
import custom_windows as cw
import tkinter as tk
class MainWindow(tk.Toplevel):
def __init__(self, master):
self.master = master
master.title("ORV application")
master.geometry("500x350")
# Set container for buttons
button_container = tk.Frame()
button_container.pack(side=tk.BOTTOM)
# Set get image button
get_image_button = tk.Button(button_container, text="Get image", command=self.click_get_image)
get_image_button.pack(padx=20, pady=10, side=tk.LEFT)
def click_get_image(self):
# Create window with image
image_window = tk.Toplevel(self.master)
cw.CustomWindow(image_window, "images/tour-de-france.jpg")
root = tk.Tk()
main_window = MainWindow(root)
root.mainloop()
From main class I called new window from class CustomWindow:
import tkinter as tk
import cv2 as cv
from PIL import Image as pilImage, ImageTk as pilImageTk
class CustomWindow(tk.Toplevel):
def __init__(self, master, image_path):
self.master = master
master.title("Image")
master.resizable(False, False)
# Open and prepare image
self.image = cv.cvtColor(cv.imread(image_path), cv.COLOR_BGR2RGB)
self.render = pilImageTk.PhotoImage(image=pilImage.fromarray(self.image))
self.height, self.width, self.no_channels = self.image.shape
# Create canvas to display image
canvas = tk.Canvas(master, width=self.width, height=self.height)
canvas.create_image(0, 0, image=self.render, anchor=tk.NW)
canvas.pack()
Image doesn't display in Canvas. I use self to save values from garbage collector.

Why is my image not showing up in tkinter canvas [duplicate]

This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 2 years ago.
I am trying to make this UI from a stimulus as part of an assessment for school. I tried to import the provided school logo and banner on the top frame of the page and put images on the canvas but have yet to achieve any results. When I run the code, the pictures won't load at all. The code that I was working with is as followed:
from tkinter import *
import random
import time
import sqlite3
from tkinter import simpledialog
from tkinter import messagebox
from tkcalendar import *
from tkinter import ttk
import math
from PIL import Image, ImageTk
import winsound
#-------------Frames setup--------------------------
class VendingApp(Tk):
def __init__(self):
Tk.__init__(self)
self._frame = None
self.switch_frame(Home)
def switch_frame(self, frame_class):
#Destroys current frame and replaces it with a new one.
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.pack()
####-----------------------Home page---------------------------
class Home(Frame):
def __init__(self, master):
Frame.__init__(self, master)
topFrame = Frame(self,width = 1024, height = 100, bd = 2, bg = "black")
topFrame.pack()
canvas_for_logo = Canvas(topFrame, height=100, width=100, bg = 'green') ##logo image
canvas_for_logo.grid(row=0, column=0, sticky='ne')
img_logo = Image.open("pic/sitelogo.png")
img_logo = img_logo.resize((40,40), Image.ANTIALIAS)
logo = ImageTk.PhotoImage(img_logo)
canvas_for_logo.create_image(0, 0, anchor=NW, image=logo)
canvas_for_banner = Canvas(topFrame, bg='red', height=100, width=924) #banner image
canvas_for_banner.grid(row=0, column=1, sticky='nw')
img_banner = Image.open("pic/banner.jpg")
img_banner = img_banner.resize((40,40), Image.ANTIALIAS)
banner = ImageTk.PhotoImage(img_banner)
canvas_for_banner.create_image(0, 0, anchor=NW, image=banner)
MidFrame = Frame(self,width = 1024, height = 628, bd = 2)
MidFrame.pack()
MidFrame.grid_propagate(False)
BottomFrame = Frame(self,width = 1024, height = 50, bd = 2, bg = "black")
BottomFrame.pack()
BottomFrame.grid_propagate(False)
if __name__ == "__main__":
root = VendingApp()
#Sets the size of the window
root.geometry("1024x768")
#Renames the TITLE of the window
root.title("Vending machine")
root.geometry("1024x768")
root.resizable(False, False)
root.mainloop()
I decided to make a separate file to test if the image would load without class, and it did. Codes are as followed:
from tkinter import ttk
from tkinter import*
import time
from PIL import Image, ImageTk
root = Tk()
canvas_for_logo = Canvas(root, height=100, width=100)
canvas_for_logo.pack()
img = Image.open("pic/sitelogo.png")
img = img.resize((105,105), Image.ANTIALIAS)
logo = ImageTk.PhotoImage(img)
canvas_for_logo.create_image(0, 0, anchor=NW, image=logo)
canvas_for_banner = Canvas(root, bg='red', height=100, width=924) #banner image
canvas_for_banner.pack()
img_banner = Image.open("pic/banner.jpg")
img_banner = img_banner.resize((924,100), Image.ANTIALIAS)
banner = ImageTk.PhotoImage(img_banner)
canvas_for_banner.create_image(0, 0, anchor=NW, image=banner)
root.mainloop()
Can someone please tell me what I did wrong? All replies are much appreciated. Thank you.
This is a typical Tkinter bug. I don't want to go into details cause I don't fully understand why it happens either, but it has something to do with the garbage collector and the fact that it doesn't consider the objects you have created for storing those images like being in use, so it deletes them; or something like that.
Luckily, it has an easy solution: you can either create an internal list variable, let say, self._images that stores each image you are using, something like:
self._images = list()
(...)
self._images.append(logo)
(...)
self._images.append(banner)
Or, you could assign to each canvas instance an attribute image (or img, it doesn't really matters) that stores the image instance it is going to carry. In your code, it will look similar to:
canvas_for_logo.image = logo
(...)
canvas_for_banner.image = banner
This way, you can avoid the garbage collector deleting what it shouldn't, cause now it acknowledges that this instances are being in use.

How to show image in tkinter using pillow with OOP

I am making a program where I need to at some point display an image onto a frame at the press of a button. I am using an object oriented approach but it won't display the image. If I do something like:
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
pic = Image.open("image.jpg")
tkpic = ImageTk.PhotoImage(pic)
label = Label(root, image=tkpic)
label.pack()
root.mainloop()
that works fine. But if I create a frame and try to display the picture like this:
from tkinter import *
from PIL import Image, ImageTk
class picframe(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
button = Button(self, text="show", command=self.showpic)
button.pack()
def showpic(self):
pic = Image.open("image.jpg")
tkpic = ImageTk.PhotoImage(pic)
label = Label(self, image=tkpic)
label.pack()
root = Tk()
frame = picframe(root)
frame.pack()
root.mainloop()
When I press the button it expands the window as if it was trying to display the image but nothing shows up it just becomes a wider window. So what am I doing wrong?
Thank you in advance!
As the picture is created in a function the reference tkpic will be garbage collected when the function exits. You need to save a reference to the image:
def showpic(self):
pic = Image.open("image.jpg")
tkpic = ImageTk.PhotoImage(pic)
label = Label(self, image=tkpic)
label.image = tkpic # Save reference to image
label.pack()
Alternatively you can ensure the persistance of the image reference by making it an instance variable:
def showpic(self):
pic = Image.open("images/beer.png")
self.tkpic = ImageTk.PhotoImage(pic)
label = Label(self, image=self.tkpic)
label.pack()

How to update the image of a Tkinter Label widget?

I would like to be able to swap out an image on a Tkinter label, but I'm not sure how to do it, except for replacing the widget itself.
Currently, I can display an image like so:
import Tkinter as tk
import ImageTk
root = tk.Tk()
img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()
However, when the user hits, say the ENTER key, I'd like to change the image.
import Tkinter as tk
import ImageTk
root = tk.Tk()
img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
def callback(e):
# change image
root.bind("<Return>", callback)
root.mainloop()
Is this possible?
The method label.configure does work in panel.configure(image=img).
What I forgot to do was include the panel.image=img, to prevent garbage collection from deleting the image.
The following is the new version:
import Tkinter as tk
import ImageTk
root = tk.Tk()
img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(root, image=img)
panel.pack(side="bottom", fill="both", expand="yes")
def callback(e):
img2 = ImageTk.PhotoImage(Image.open(path2))
panel.configure(image=img2)
panel.image = img2
root.bind("<Return>", callback)
root.mainloop()
The original code works because the image is stored in the global variable img.
Another option to do it.
Using object-oriented programming and with an interactive interface to update the image.
from Tkinter import *
import tkFileDialog
from tkFileDialog import askdirectory
from PIL import Image
class GUI(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
w,h = 650, 650
master.minsize(width=w, height=h)
master.maxsize(width=w, height=h)
self.pack()
self.file = Button(self, text='Browse', command=self.choose)
self.choose = Label(self, text="Choose file").pack()
self.image = PhotoImage(file='cualitativa.gif')
self.label = Label(image=self.image)
self.file.pack()
self.label.pack()
def choose(self):
ifile = tkFileDialog.askopenfile(parent=self,mode='rb',title='Choose a file')
path = ifile.name
self.image2 = PhotoImage(file=path)
self.label.configure(image=self.image2)
self.label.image=self.image2
root = Tk()
app = GUI(master=root)
app.mainloop()
root.destroy()
Replace 'cualitativa.jpg' for the default image you want to use.
Another solution that might be of help.
In my case, I had two tk.Tk() windows. When using ImageTk.PhotoImage(), the object defaults to setting its tk window to being the first one created. A simple fix to this is to pass the tk window that you want as such ImageTk.PhotoImage(img, master=your_window)
import tkinter as tk
from PIL import ImageTk, Image
if __name__ == '__main__':
main_window = tk.Tk()
second_window = tk.Tk()
main_canvas = Canvas(second_window)
main_canvas.pack()
filename = 'test.png'
img = Image.open(filename)
img = img.resize((300, 100), Image.ANTIALIAS)
logo = ImageTk.PhotoImage(img, master=second_window)
logo_label = Label(master=main_canvas, image=logo)
logo_label.image = logo
logo_label.pack()
main_window.mainloop()

Categories