Python tkinter create image with different layers? - python

I would like to give layers to tkinter images when we created them below code:
from tkinter import *
canvas_width = 300
canvas_height =300
master = Tk()
canvas = Canvas(master,
width=canvas_width,
height=canvas_height)
canvas.pack()
mylist = []
img = PhotoImage(file="./Images/screwsmall.png")
mylist.append (canvas.create_image(20,20, anchor=NW, image=img))
img_2 = PhotoImage(file="./Images/screwsmall.png")
mylist.append (canvas.create_image(50,20, anchor=NW, image=img_2))
mainloop()
As you can see two images are created, however the second image is on top of first image. How can I decide their layers by the code? In other words can I make the first image go on top of other with out creating order?

Use the tag_lower() and tag_raise() methods for the Canvas object:
canvas.tag_raise(mylist[0]) # move the first image to the top

Related

How to center an image in tkinter with PIL

I want to center an image in tkinter canvas. The only thing I could think of is using anchor = 'c' but that does not seem to work. I have also tried using it on the stage.
def newsetup(filelocation):
global width, height
for widgets in root.winfo_children():
widgets.destroy()
stage = Canvas(root, width = 1000, height = 700, highlightbackground = 'red', highlightthickness = 2)
stage.pack()
imgtk = ImageTk.PhotoImage(Image.open(filelocation))
stage.create_image(stage.winfo_width() + 2, stage.winfo_height() + 2, image = imgtk, anchor = CENTER)
stage.image = imgtk
if you want to center on canvas then you need
stage.winfo_width()/2, stage.winfo_height()/2
(even without anchor= which as default has value center)
But if you put image before it runs mainloop() then stage.winfo_width() stage.winfo_height() gives 0,0 instead of expected width, height (because mainloop creates window and it sets all sizes for widgets) and it may need root.update() to run mainloop once and it will calculate all sizes.
import tkinter as tk
from PIL import ImageTk, Image
root = tk.Tk()
stage = tk.Canvas(root, width=1000, height=700)
stage.pack()
root.update() # force `mainloop()` to calculate current `width`, `height` for canvas
# and later `stage.winfo_width()` `stage.winfo_height()` will get correct values instead `0`
#imgtk = ImageTk.PhotoImage(Image.open('lenna.png'))
imgtk = ImageTk.PhotoImage(file='lenna.png')
stage.create_image((stage.winfo_width()/2, stage.winfo_height()/2), image=imgtk, anchor='center')
stage.image = imgtk
root.mainloop()
Result:
Image Lenna from Wikipedia.
EDIT:
If you want to keep it centered when you resize window then you can bind event <Configure> to canvas and it will execute assigned function - and it can move image.
But it needs image ID which you can get when you create image
img_id = stage.create_image(...)
Because <Configure> is executed when it creates window so code doesn't need root.update() because on_resize() will set correct position at start.
import tkinter as tk
from PIL import ImageTk, Image
# --- functions ---
def on_resize(event):
# it respects anchor
x = event.width/2
y = event.height/2
stage.coords(img_id, x, y)
# it DOESN'T respects anchor so you have to add offset
#x = (event.width - imgtk.width())/2
#y = (event.height - imgtk.height())/2
#stage.moveto(img_id, x, y) # doesn't respect anchor
#stage.itemconfigure(img_id, ...)
# --- main ---
root = tk.Tk()
stage = tk.Canvas(root, width=1000, height=700)
stage.pack(fill='both', expand=True)
#root.update() # force `mainloop()` to calculate current `width`, `height` for canvas
# and later `stage.winfo_width()` `stage.winfo_height()` will get correct values instead `0`
#imgtk = ImageTk.PhotoImage(Image.open('lenna.png'))
imgtk = ImageTk.PhotoImage(file='lenna.png')
img_id = stage.create_image((stage.winfo_width()/2, stage.winfo_height()/2), image=imgtk, anchor='center')
stage.image = imgtk
stage.bind('<Configure>', on_resize) # run function when Canvas change size
root.mainloop()

Tkinter - rotate image with slider simultaneously

UPDATED -
New to tkinter
Is it possible to rotate a picture by using a slider simultaneously.
I have an image of a rotatory dial, beneath this image is a slider listed from 0 to 360. I would like the image to rotate clockwise as the slider is moved from 0 to 360, and anticlockwise as the slider is returned from 360 to 0.
ROTATION OF IMAGE WITH SLIDER WORKS CORRECTLY
I have ran into a bug, the image is black. Perhaps the image is too zoomed in? Apologies, I am new to python and tkinter.
Here is how the GUI should look Correct GUI
THIS IS HOW THE GUI LOOKS NOW Incorrect GUI with Slider
THIS IS HOW THE GUI LOOKS REMOVING THUMBNAIL LINE THUMBNAIL
Here is the updated code
# import necessary modules
from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk
root = Tk()
root.title("Gesture Detection Application")
root.geometry("400x320") # set starting size of window
root.maxsize(400, 320) # width x height
root.config(bg="#6FAFE7") # set background color of root window
Heading = Label(root, text="Demonstrator Application2", bg="#2176C1", fg='white', relief=RAISED)
Heading.pack(ipady=5, fill='x')
Heading.config(font=("Font", 20)) # change font and size of label
image = Image.open("rotate_dial.png")
width, height = image.size
image.thumbnail((width/5, height/5))
photoimage = ImageTk.PhotoImage(image)
image_label = Label(root, image=photoimage, bg="white", relief=SUNKEN)
image_label.image = photoimage
image_label.pack(pady=5)
def rotate_image(degrees):
new_image = image.rotate(-int(degrees))
photoimage = ImageTk.PhotoImage(new_image)
image_label.image = photoimage #Prevent garbage collection
image_label.config(image = photoimage)
w2 = Scale(root, from_=0, to=360, tickinterval= 30, orient=HORIZONTAL, length=300, command = rotate_image)
w2.pack()
w2.set(0)
root.mainloop()
You can rotate the image using PIL (which you've already imported). You can link it to the Scale by adding a command.
image = Image.open("rotate_dial.png")
width, height = image.size
image.thumbnail((width/5, height/5))
photoimage = ImageTk.PhotoImage(image)
image_label = Label(root, image=photoimage, bg="white", relief=SUNKEN)
image_label.pack(pady=5)
def rotate_image(degrees):
new_image = image.rotate(-int(degrees))
photoimage = ImageTk.PhotoImage(new_image)
image_label.image = photoimage #Prevent garbage collection
image_label.config(image = photoimage)
w2 = Scale(root, from_=0, to=360, tickinterval= 30, orient=HORIZONTAL, length=300, command = rotate_image)
Instead of creating a PhotoImage initially, it now creates a PIL Image object. It then uses the height and width and the thumbnail function to replace the subsample. Then it uses ImageTk to turn it into a tkinter PhotoImage which is shown in the label. The Scale now has a command, rotate_image, which recieves the scale value, which is the number of degrees, and then uses PIL to create a new rotated image, which is then turned into a PhotoImage and displayed in the label by changing it's image with .config. Now when you move the slider, the image rotates with it.

Is it possible to provide animation on image ? - Tkinter

I'm developing a GUI in Tkinter and want to apply animation in the below GIF on the image when it appears.
Here is my code,
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
frame = Frame(root)
frame.pack()
canvas = Canvas(frame, width=300, height=300, bd=0, highlightthickness=0, relief='ridge')
canvas.pack()
background = PhotoImage(file="background.png")
canvas.create_image(300,300,image=background)
my_pic = PhotoImage(file="start000-befored.png")
frame.after(1000, lambda: (canvas.create_image(50,50,image=my_pic, anchor=NW))) #and on this image, I want to give the effect.
root.mainloop()
Instead of clicking on the play button as shown in GIF, the image should automatically appears after 1 second like this animation and stays on screen. (No closing option).
I'm not 100% sure I understood the problem, but I'll describe how to animate an image.
Tkinter does not contain functions for animating images so you'll have to write them yourself. You will have to extract all subimages, subimage duration and then build a sequencer to swap subimages on your display.
Pillow can extract image sequences. WEBP images seems to only support one frame duration whereas GIF images may have different frame duration for each subimage. I will use only the first duration for GIF images even if there is many. Pillow does not support getting frame duration from WEBP images as far as I have seen but you gan read it from the file, see WebP Container Specification.
Example implementation:
import tkinter as tk
from PIL import Image, ImageTk, ImageSequence
import itertools
root = tk.Tk()
display = tk.Label(root)
display.pack(padx=10, pady=10)
filename = 'images/animated-nyan-cat.webp'
pil_image = Image.open(filename)
no_of_frames = pil_image.n_frames
# Get frame duration, assuming all frame durations are the same
duration = pil_image.info.get('duration', None) # None for WEBP
if duration is None:
with open(filename, 'rb') as binfile:
data = binfile.read()
pos = data.find(b'ANMF') # Extract duration for WEBP sequences
duration = int.from_bytes(data[pos+12:pos+15], byteorder='big')
# Create an infinite cycle of PIL ImageTk images for display on label
frame_list = []
for frame in ImageSequence.Iterator(pil_image):
cp = frame.copy()
frame_list.append(cp)
tkframe_list = [ImageTk.PhotoImage(image=fr) for fr in frame_list]
tkframe_sequence = itertools.cycle(tkframe_list)
tkframe_iterator = iter(tkframe_list)
def show_animation():
global after_id
after_id = root.after(duration, show_animation)
img = next(tkframe_sequence)
display.config(image=img)
def stop_animation(*event):
root.after_cancel(after_id)
def run_animation_once():
global after_id
after_id = root.after(duration, run_animation_once)
try:
img = next(tkframe_iterator)
except StopIteration:
stop_animation()
else:
display.config(image=img)
root.bind('<space>', stop_animation)
# Now you can run show_animation() or run_animation_once() at your pleasure
root.after(1000, run_animation_once)
root.mainloop()
There are libraries, like imgpy, which supports GIF animation but I have no experience in usig any such library.
Addition
The duration variable sets the animation rate. To slow the rate down just increase the duration.
The simplest way to put the animation on a canvas it simply to put the label on a canvas, see example below:
# Replace this code
root = tk.Tk()
display = tk.Label(root)
display.pack(padx=10, pady=10)
# with this code
root = tk.Tk()
canvas = tk.Canvas(root, width=500, height=500)
canvas.pack(padx=10, pady=10)
display = tk.Label(canvas)
window = canvas.create_window(250, 250, anchor='center', window=display)
Then you don't have to change anything else in the program.

How to make background Transparent in TKinter by converting Label widget into Canvas widget?

I have a code that is working perfectly but it's not giving me transparent background, (here is the image ) after a research on web, I found the solution by using canvas widget, we can us images with transparent background.
Here is my code,
import tkinter as tk
from PIL import Image, ImageTk
def work(progress=1):
if progress > 300: # define the width by yourself
return
tmp_images = ImageTk.PhotoImage(progress_images.resize((progress, 10))) # the image size
lb.image = tmp_images # keep reference
lb["image"] = tmp_images # change the image
root.add = root.after(100, work, progress+10) # define the amplitude by yourself
root = tk.Tk()
progress_images = Image.open("path.png")
lb = tk.Label(root, bg="black")
lb.pack(side="left")
work()
root.mainloop()
but I am confused how to change Label widget into Canvas ? can anyone help me please ? I am noob in Tkinter still!!!
You can use canvas.create_text(...) to replace the labels and then use canvas.itemconfig(...) to update the labels. I got this from an other stack over flow question
reference link :-
add label ..
Below is a modified code using Canvas:
import tkinter as tk
from PIL import Image, ImageTk
def work(progress=10):
if progress > 300: # define the width by yourself
return
canvas.image = ImageTk.PhotoImage(progress_images.resize((progress, 30))) # the image size
canvas.itemconfig(pbar, image=canvas.image) # update image item
root.add = root.after(100, work, progress+10) # define the amplitude by yourself
root = tk.Tk()
progress_images = Image.open("path.png")
canvas = tk.Canvas(root, width=300, height=30, bg='black', highlightthickness=0)
canvas.pack()
pbar = canvas.create_image(0, 0, anchor='nw') # create an image item
work()
root.mainloop()

Unable to draw to canvas in Tkinter after() loop

I'm having a problem that when i try to create an image on the canvas i am unable to produce the image. However before my after() loop is initiated i am able to create and configure my images. Also, i am able to remove objects from my canvas using canvas.delete() in my after() loop so i do still have some level of control.
I am on windows 8.1, using Python 3.5.4
import tkinter as tk
from PIL import Image, ImageTk
from math import floor
import numpy as np
from scipy import ndimage
root = tk.Tk()
HEIGHT = 600
WIDTH = 600
CANVAS_MID_X = WIDTH / 2
CANVAS_MID_Y = HEIGHT / 2
def my_mainloop():
#THIS WORKS!!! REMOVES THE DIAL CREATED BEFORE THE MAINLOOP
canvas.delete(dial_1)
#THIS WORKS BELOW BEFORE MAINLOOP, BUT NOT IT WONT WORK! (use opencv?)
img = dial_1_img_resized
img2 = img.rotate(45, expand=True)
dial_1_photo_new = ImageTk.PhotoImage(img2)
dial_2 = canvas.create_image((dial_1_center), image=dial_1_photo_new, anchor=tk.E)
'''CANT DRAW TO CANVAS IN AFTER LOOP'''
print("loop!")
root.after(4000,my_mainloop)
'''-------------------Create Canvas, and starting dials in their starting positions---------------------'''
canvas = tk.Canvas(root, width=HEIGHT, height=WIDTH, bg="black")
canvas.grid(row=0, column=0)
dial_1_path = "gauge1.png"
dial_1_width = 400
dial_1_img = Image.open(dial_1_path, 'r') #open image
dial_1_img_ratio = int(dial_1_img.size[1]) / int(dial_1_img.size[0])
dial_1_img_resized = dial_1_img.resize((dial_1_width, floor(dial_1_img_ratio * dial_1_width)), 1)
dial_1_photo = ImageTk.PhotoImage(dial_1_img_resized)
dial_1_center = (CANVAS_MID_X, CANVAS_MID_Y)
#CREATE DIAL ON CANVAS, THIS WORKS!!
dial_1 = canvas.create_image((dial_1_center), image=dial_1_photo)
'''Start Main Loop'''
root.after(0, my_mainloop)
root.mainloop()
Therefore my question is: is there a way to manipulate and create canvas images in the after() loop? (called my_mainloop) any help is appreciated!
You'll need to save a reference to your photo because it is being garbage collected after my_mainloop runs. You can add it to your canvas object for instance:
canvas.dial_1_photo_new = ImageTk.PhotoImage(img2)
dial_2 = canvas.create_image((dial_1_center), image=canvas.dial_1_photo_new, anchor=tk.E)

Categories