Tkinter Display picture when calling function - python

I wanted to display a picture .png in tkinter when calling a function (but it could also be with a boolean showOnOff).
This is what I wrote for the moment, but the picture doesn't appear. Do you have any idea ?
from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk
root = Tk()
def display():
# Use library PIL to display png picture
path = '3d.png'
img = ImageTk.PhotoImage(Image.open(path), Image.ANTIALIAS)
panel = Label(root, image = img)
panel.grid(row=1, column=0)
ButtonDisplay = ttk.Button(root, text="Display", command=display)
ButtonDisplay.grid(row=0, column=0)
root.mainloop()

The problem is the definition of the image which is only local inside the funtion. If you make the image global, it works:
def display():
global img
# Use library PIL to display png picture
path = '3d.png'
img = ImageTk.PhotoImage(Image.open(path))
panel = Label(root, image=img)
panel.grid(row=1, column=0)

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: Does anyone know how to change a button into a image?

This is my code for the button that opens an app:
Modules:
import tkinter as tk
from tkinter import *
from PIL import ImageTk, Image
from subprocess import Popen
Importing Image:
path = ("C:\Pictures\GoogleLogo.png")
img = Image.open(path)
img = img.resize((96, 96), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
Generic Canvas Button:
def openCalc():
Popen("calc.exe")
openCalcWin = tk.Button(text='Calculator', command=openCalc, bg="Grey", height = 6, width = 10)
canvas.create_window(1167,714, window=openCalcWin)
What I have Tried:
I attempted to make the background of the button into an image by using bg or img. But this just creates an tiny image logo that can't be clicked. Indicating that there was an error loading the image, but there was no error code or anything in the IDLE Shell.
There was other attempts of code that I forgot, but most of them ends up the same: no button appeared and no error code.
Edit:
import tkinter as tk
from PIL import ImageTk, Image
from subprocess import Popen
##Application Window:
root=tk.Tk()
root.title("Virtual Desktop")
root.resizable(False, False)
#Determine Window Resolution
canvas = tk.Canvas(root, width=1280, height=780, bg="#263D42")
canvas.pack()
#Importing Calulator Image
path = ("C:\Pictures\CalcLogo.png")
img = Image.open(path)
img = img.resize((96, 96), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
#Calculator Button
def openCalc():
Popen("calc.exe")
openCalcWin = tk.Button(text='Calculator', command=openCalc, bg="Grey", height = 6, width = 10)
canvas.create_window(1167,714, window=openCalcWin)
The following works for me. The most important change was to specify an image= keyword argument, when creating the Button.
The other thing I noted was the:
path = ("C:\Pictures\CalcLogo.png")
you had. The parentheses are unnecessary (but don't hurt), however you need to add an r prefix to all strings containing back-slash characters like paths on Windows.
path = r"C:\Pictures\CalcLogo.png"
or just use forward-slashes (which work fine on Windows):
path = "C:/Pictures/CalcLogo.png"
Full code:
import tkinter as tk
from PIL import ImageTk, Image
from subprocess import Popen
##Application Window:
root=tk.Tk()
root.title("Virtual Desktop")
root.resizable(False, False)
#Determine Window Resolution
canvas = tk.Canvas(root, width=1280, height=780, bg="#263D42")
canvas.pack()
#Importing Calulator Image
path = "8-ball.png" # My own image.
img = Image.open(path)
img = img.resize((96, 96), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
#Calculator Button
def openCalc():
Popen("calc.exe")
openCalcWin = tk.Button(text='Calculator', command=openCalc, bg="Grey",
image=img)
canvas.create_window(1167,714, window=openCalcWin)
root.mainloop()
I found this solution. You can check it learn about it yourself, but basically you do not provide any args when creating the obj/Button, you only provide the root, image and command, and it should work.
Something like this:
import tkinter as tk
from tkinter import *
from PIL import ImageTk, Image
from subprocess import Popen
root = Tk()
path = ("C:\Pictures\GoogleLogo.png")
img = Image.open(path)
img = img.resize((96, 96), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
def openCalc():
Popen("calc.exe")
openCalcWin = tk.Button(text='Calculator', image=img, command=openCalc)
openCalcWin.pack()
root.mainloop()
if you want, you can look at some examples and learn more here - https://www.activestate.com/resources/quick-reads/how-to-add-images-in-tkinter/

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

Replace Canvas Image in Tkinter

I have a program and I want when someone clicks a button, the canvas image will change. My code is below:
from PIL import ImageTk,Image, ImageFont, ImageDraw
import tkinter
import textwrap
from tkinter import Frame, Canvas, Text, INSERT, END
root = tkinter.Tk()
root.geometry("296x337")
root.resizable(False, False)
im=Image.open("red.jpg")
photo=ImageTk.PhotoImage(im)
cv = tkinter.Canvas()
cv.pack(side='top', fill='both', expand='yes')
cv.create_image(0, 0, image=photo, anchor='nw')
def changepic():
###place where I want to change the Canvas Image
print("change color")#I added this because python wouldn't let me run thee function without something.
a2=tkinter.Button(root,text='change color',bd=0, command=changepic)
a2.config(highlightbackground='black')
a2.place(x=135, y=70)
Instead of using Canvas, I replaced the code so that it prints the image using tkinter.Label:
from PIL import ImageTk,Image, ImageFont, ImageDraw
import tkinter
import textwrap
from tkinter import Frame, Canvas, Text, INSERT, END
root = tkinter.Tk()
root.geometry("296x337")
root.resizable(False, False)
img = ImageTk.PhotoImage(Image.open("red.jpg"))
panel = tkinter.Label(root, image=img)
panel.pack(side="bottom", fill="both", expand="yes")
def changepic(imagename):
img2 = ImageTk.PhotoImage(Image.open(imagename))
panel.configure(image=img2)
panel.image = img2
a2=tkinter.Button(root,text='change color',bd=0, command=changepic("blue.jpg")
a2.config(highlightbackground='black')
a2.place(x=135, y=70)
I got my information from: How to update the image of a Tkinter Label widget?
And: https://www.tutorialspoint.com/python/tk_label.htm

Display an image tkinter macOSX [duplicate]

How do I insert a JPEG image into a Python 2.7 Tkinter window? What is wrong with the following code? The image is called Aaron.jpg.
#!/usr/bin/python
import Image
import Tkinter
window = Tkinter.Tk()
window.title("Join")
window.geometry("300x300")
window.configure(background='grey')
imageFile = "Aaron.jpg"
window.im1 = Image.open(imageFile)
raw_input()
window.mainloop()
Try this:
import tkinter as tk
from PIL import ImageTk, Image
#This creates the main window of an application
window = tk.Tk()
window.title("Join")
window.geometry("300x300")
window.configure(background='grey')
path = "Aaron.jpg"
#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
img = ImageTk.PhotoImage(Image.open(path))
#The Label widget is a standard Tkinter widget used to display a text or image on the screen.
panel = tk.Label(window, image = img)
#The Pack geometry manager packs widgets in rows or columns.
panel.pack(side = "bottom", fill = "both", expand = "yes")
#Start the GUI
window.mainloop()
Related docs: ImageTk Module, Tkinter Label Widget, Tkinter Pack Geometry Manager
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
win = tk. Tk()
image1 = Image. open("Aoran. jpg")
image2 = ImageTk. PhotoImage(image1)
image_label = ttk. Label(win , image =.image2)
image_label.place(x = 0 , y = 0)
win.mainloop()
from tkinter import *
from PIL import ImageTk, Image
window = Tk()
window.geometry("1000x300")
path = "1.jpg"
image = PhotoImage(Image.open(path))
panel = Label(window, image = image)
panel.pack()
window.mainloop()

Categories