Why does my PhotoImage doesn't shows up in tkinter? - python

it's my first question here.
I use tkinter with python3.9 for displaying an image, a flag of which country it shows up on the window
# gets the img flag
flag = PhotoImage(file=flagsFolder+countryList[rand_label]) # the path is "D:\Images\Flags of the world" + "XXXX.gif"
# creates the img Label
flagLabel = Label(frame, image=flag)
flagLabel.place(x=window_width/2, y=200, anchor='center')
So, when I try to display the image, it shows me this:
A flag should be here instead of the white image.
Why isn't it showing up?

So I messed around a bit and found out a solution.
I had to use ImageTk from Pillow so:
from PIL import ImageTk
Then, instead of creating a Label for my image, I made a Canvas:
# notice how I used ImageTk.PhotoImage instead of the basic PhotoImage from Tkinter
img = ImageTk.PhotoImage(file='filename.png')
# creates the img Canvas
imgCanvas = Canvas(frame)
imgCanvas.place(x=window_width/2, y=200, anchor='center', width=img.width(), height=img.height())
imgCanvas.create_image(0, 0, anchor=NW, image=img)
imgCanvas.image = img # now the image displays perfectly :D
The final result:

Related

Tkinter - Python3 Does Not Show The Image When Clicked [duplicate]

This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 8 months ago.
I've tried several methods but did not worked. Suppose I am working on a project that changes the picture when the button is clicked.
Well as I know, all it did is I just clicked 1 time and the image turned white and I can not click it anymore. Quick! I need to complete this project in 1 hour deadline. Here is the code.
# Modules
from tkinter import *
from PIL import Image, ImageTk
# Functions
def change_img():
global curr_img
global root
global image1
image1 = Image.open(f"Hamster {curr_img + 1}.jpg")
image1 = image1.resize((100, 60))
img1 = ImageTk.PhotoImage(image1)
btn.configure(image=img1, command=change_img)
root.update()
curr_img += 1
# Main Window
root = Tk()
root.title("Picture Change")
root.geometry("300x150")
root.config(bg="black")
# Adding Objects
curr_img = 1
Label(root, text="My Favorite Animal", fg="white", bg="black", font=("Arial bold", "20")).pack() # This is a label.
image1 = Image.open("Hamster 1.jpg") # First we open the image and save it into a variable.
image1 = image1.resize((100,60)) # Resizes the image.
img1 = ImageTk.PhotoImage(image1) # Create a ImageTK object from the image1 variable.
btn = Button(image = img1, command=change_img) # Create a label and put the image into it.
btn.pack() # Pack the label that contains the image. Now, we repeat the process.
# Mainloop
root.mainloop()
Thanks if the answer is quick and accurate. Comment, thanks very much too.
You create the next image in the change_img() function and when the function exits the reference to the image is garbage collected. You can save a reference to the image in the button widget:
btn.configure(image=img1, command=change_img)
btn.image = img1 # Save a reference to the new image

is there a way to remove white outline when placing image on tk window?

When I try to add an image from another directory to the tk window.
This is the png file.This is what appears in the tk window The image has a white outline around it. The png file has no white outline so there must problem when its being added to the tk window. Here is the code so far below :
from tkinter import *
from PIL import Image, ImageTk
window = Tk()
window.configure(bg = '#73767A')
im = Image.open("static/logo.png")
im = ImageTk.PhotoImage(im.resize((400,225), Image.ANTIALIAS))
Label(image = im).place(x = 200, y = 0)
You can set the borderwidth and highlightthickness attributes to zero.

How can I remove blur / blur and rotate at the same time?

I am a beginner in python and learning about PIL and tkinter.
Now what I am trying is to edit a image and I am struggling from blur and rotate.
When I blur an image, I cannot get rid of it without rotating it. (I want to make a button to on/off blur)
And if I blur/rotate an image,
Another one doesn't work at the same time.
How can I solve this problem? here is my code
import tkinter as tk
from PIL import Image, ImageTk, ImageFilter
from tkinter import filedialog as fd
img=None
tk_img=None
angle=0
def open():
global img, tk_img
filename=fd.askopenfilename()
img=Image.open(filename)
tk_img=ImageTk.PhotoImage(img)
canvas.create_image(250,250,image=tk_img)
window.update()
def quit():
window.destroy()
def image_rotate():
global img,tk_img,angle
angle=angle+45
tk_img=ImageTk.PhotoImage(img.rotate(angle))
canvas.create_image(250,250,image=tk_img)
window.update()
def image_blur():
global img,tk_img
tk_img=ImageTk.PhotoImage(img.filter(ImageFilter.BLUR))
canvas.create_image(250,250,image=tk_img)
window.update()
window = tk.Tk() #윈도우 생성
canvas=tk.Canvas(window,width=500,height=500)
canvas.pack()
menubar = tk.Menu(window) #메뉴바 생성
filemenu = tk.Menu(menubar) #파일메뉴를 메뉴바에 달아줌
filemenu.add_command(label="picture", command=open)
filemenu.add_command(label="exit", command=quit)
menubar.add_cascade(label="파일", menu=filemenu)
imagemenu=tk.Menu(menubar)
imagemenu.add_command(label="rotate",command=image_rotate)
imagemenu.add_command(label="blur",command=image_blur)
menubar.add_cascade(label="movement", menu=imagemenu)
window.config(menu=menubar)
window.mainloop()
The reason is quite obvious, your img object as seen is only defined/updated in open(), so the image will always refer to the original image selected and not the new edited image, so to show the change store it in a new variable and then globalize it.
Also note that you are creating a new canvas image every time you call the function, which is not efficient, so make a single canvas image and then update it each time, inside the function using itemconfig() method.
def open():
global img, tk_img
filename = fd.askopenfilename()
img = Image.open(filename)
tk_img = ImageTk.PhotoImage(img)
canvas.itemconfig('img',image=tk_img) # Update image
def image_rotate():
global tk_img, angle, img
angle += 45 # More pythonic to always use += rather than a = a + 10
img = img.rotate(angle)
tk_img = ImageTk.PhotoImage(img)
canvas.itemconfig('img',image=tk_img) # Update image
angle -= 45
def image_blur():
global tk_img, img
img = img.filter(ImageFilter.BLUR)
tk_img = ImageTk.PhotoImage(img)
canvas.itemconfig('img',image=tk_img) # Update image
canvas = tk.Canvas(window,width=500,height=500)
canvas.create_image(250,250,tag='img') # Create initial canvas object
canvas.pack()
Also take a look at how I formatted your code to make it look more near, follow PEP 8 -- Style Guide for Python Code for more.
You can blur the image using opencv package
import cv2
img = cv2.imread('imagepath')
blurImg = cv2.blur(img,(10,10))
cv2.imshow('blurred image',blurImg)
cv2.waitKey(0)
cv2.destroyAllWindows()
Or u can check the documentation of opencv to blurr the image.
U can also rotate image using opencv
# importing cv2
import cv2
src = cv2.imread(path)
window_name = 'Image'
image = cv2.rotate(src, cv2.ROTATE_90_COUNTERCLOCKWISE)
# Displaying the image
cv2.imshow(window_name, image)
cv2.waitKey(0)

how to change labels background as same picture

I started to learn Python one month ago. Sorry if my question is not good, this is my first question here.
I have made a small game using tkinter, but I have a problem.
I made a big label with a picture on it as background. Whenever I make more labels with text on them, the text will have gray background. However what I want is for every text to have the picture that I already placed as background.
Here's some code to explain it:
from tkinter import*
x=Tk()
x.geometry("1000x1000")
z=PhotoImage(file="D:\\Blue.gif")
v=Label(x,text="hi",font=100,fg="red",compound=CENTER,image=z,width=1000,height=1000)
v.place(x=0,y=0)
v1=Label(x,text="OO",font=100,fg="red")
v1.place(x=300,y=400)
x.mainloop()
The v label works very well as long as I use compound with it. It shows the picture with the text "hi" on it.
However I want the v1 label to have the same background as v, instead of gray background.
All widgets have background - they can't be transparent.
You can use tk.Canvas to put text without background on image or transparent image on text.
effbot.org: Canvas, PhotoImage
#!/usr/bin/env python3
import tkinter as tk
from PIL import Image, ImageTk
# --- constants ---
WIDTH = 800
HEIGHT = 600
# --- main ---
root = tk.Tk()
c = tk.Canvas(root, width=WIDTH, height=HEIGHT)
c.pack()
# only GIF and PGM/PPM
#photo = tk.PhotoImage(file='test.gif')
# other formats
image = Image.open('test_transparent.png')
photo = ImageTk.PhotoImage(image)
# use in functions - solution for "garbage collector" problem
c.image = photo
i = c.create_image((WIDTH//2, HEIGHT//2), image=photo)
t = c.create_text((WIDTH//2, HEIGHT//2), text='Hello World')
root.mainloop()
Change order and you get image on text
t = c.create_text((WIDTH//2, HEIGHT//2), text='Hello World')
i = c.create_image((WIDTH//2, HEIGHT//2), image=photo)
test_transparent.png (image with transparent background)

How do I place an image (.png) within a `LabelFrame`, and resize it, in Tkinter?

I'm trying to place a .png image within a LabelFrame in a Tkinter window. I imported PIL so .png image types should be supported (right?). I can't seem to get the image to show up.
Here is my revised code:
import Tkinter
from Tkinter import *
from PIL import Image, ImageTk
root = Tk()
make_frame = LabelFrame(root, text="Sample Image", width=150, height=150)
make_frame.pack()
stim = "image.png"
width = 100
height = 100
stim1 = stim.resize((width, height), Image.ANTIALIAS)
img = ImageTk.PhotoImage(image.open(stim1))
in_frame = Label(make_frame, image = img)
in_frame.pack()
root.mainloop()
With this code, I got an AttributeError that reads: "'str' has no attribute 'resize'"
#Mickey,
You have to call the .resize method on the PIL.Image object and not the filename, which is a string. Also, you may prefer to use PIL.Image.thumbnail instead of PIL.Image.resize, for reasons described clearly here. Your code was close, but this might be what you need:
import Tkinter
from Tkinter import *
from PIL import Image, ImageTk
root = Tk()
make_frame = LabelFrame(root, text="Sample Image", width=100, height=100)
make_frame.pack()
stim_filename = "image.png"
# create the PIL image object:
PIL_image = Image.open(stim_filename)
width = 100
height = 100
# You may prefer to use Image.thumbnail instead
# Set use_resize to False to use Image.thumbnail
use_resize = True
if use_resize:
# Image.resize returns a new PIL.Image of the specified size
PIL_image_small = PIL_image.resize((width,height), Image.ANTIALIAS)
else:
# Image.thumbnail converts the image to a thumbnail, in place
PIL_image_small = PIL_image
PIL_image_small.thumbnail((width,height), Image.ANTIALIAS)
# now create the ImageTk PhotoImage:
img = ImageTk.PhotoImage(PIL_image_small)
in_frame = Label(make_frame, image = img)
in_frame.pack()
root.mainloop()

Categories

Resources