Tkinter - rotate image with slider simultaneously - python

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.

Related

Tkinker and online resizing of .jpg with Pillow (PIL)

Trying to include a slider to resize images online in a Tkinker-GUI-Application of python.
Problem: Canvas Resizing works, Inital Show of original sized image, too. But when using the slider the picture is not resized - it just shows very short in the adjusted size and is then somehow "overwritten" by the original one.
from tkinter import *
from turtle import width
from PIL import Image, ImageTk
import FileDownloader
window = Tk()
window.title ('Price Catcher')
#PIL to open a jpg and store a Tk compatible objekct
headerpic = Image.open("./10374_0.jpg")
def resizePictures(scalerValue):
print(scalerValue)
print(window.canvas.find_all())
headerpicTk = ImageTk.PhotoImage(headerpic.resize((int(scalerValue), int(scalerValue)), Image.ANTIALIAS))
window.canvas.config(width=int(scalerValue), height=int(scalerValue))
#window.canvas.delete("all")
canvas_id = window.canvas.create_image(0,0, anchor=NW, image=headerpicTk)
window.canvas.update()
#Picture Resizer
PicResizeScale = IntVar() #Control Variable to use for Picture Resizing Value of Scaler
window.scale = Scale(window, label='Bildgröße in %', orient=HORIZONTAL, resolution=10, length=300, from_=0, to=200, command=resizePictures)
window.scale.set(100)
window.scale.pack(side=TOP)
#PIL to open a jpg and store a Tk compatible objekct
headerpic = Image.open("./10374_0.jpg")
headerpicTk = ImageTk.PhotoImage(headerpic)
#Place the opject to the canvas
window.canvas = Canvas(window, width=100, height=100)
window.canvas.pack()
canvas_id = window.canvas.create_image(0,0, anchor=NW, image=headerpicTk)
window.downloadbutton = Button(window, text='Download Bild', command=FileDownloader.FileDownloader("https://www.silbertresor.de/images/product_images/info_images/10374_0.jpg", ".\\10374_0.jpg"), justify= LEFT)
window.downloadbutton.pack(side = BOTTOM)
window.exitbutton = Button(window, text='Schließen', command=exit, justify= RIGHT)
window.exitbutton.pack(side= BOTTOM)
window.mainloop()
Any hints - i'm lost :(..
PhotoImage has bug which removes image when it is assigned to local variable in function.
And inside resizePictures you assign new PhotoImage to local variable headerpicTk.
You have to add global headerpicTk to assign PhotoImage to global variable headerpicTk.
def resizePictures(scalerValue):
global headerpicTk
print(scalerValue)
# ...rest ...
That's all.

How do I make a canvas and a photo the same size on Tkinter?

I'm making a photo watermark programme using Python and Tkinter. Basically it allows the user to upload a photo and create a text watermark to put over the photo.
I'm working on a function so that the user can move the text watermark to wherever they want on the photo based on the x and y coordinates. Therefore, I'm trying to have the canvas be the same height and width as the photo so the user can easily play around with the watermark placement.
However, the canvas always seems to be bigger than the photo that gets uploaded and I'm not really sure why.
Here's the code I have so far, that takes the height and width of the photo and sets them as the size of the canvas. I've then halved them for the placement of the photo uploaded so that the photo is right in the middle of the canvas.
import tkinter
from tkinter import filedialog
from PIL import ImageTk
from tkinter import *
from PIL import Image
window = tkinter.Tk()
window.title("Image Watermarker")
window.config(padx=50, pady=10, bg='#ADD8E6', width=1000, height=1000)
# Choose photo to watermark, adds to window
upload = filedialog.askopenfilename(initialdir='/', title="Select an Image",
filetypes=(('png files', '*.png'), ('jpeg files', '*.jpeg')))
photo = ImageTk.PhotoImage(Image.open(upload))
h = photo.height()
w = photo.width()
canvas = Canvas(window, width=w, height=h, highlightthickness=0)
canvas.create_image((h / 2), (w / 2), image=photo, anchor=CENTER)
canvas.pack()
Change the line to:
canvas.create_image((w/2), (h/2), image=photo, anchor=CENTER)
as you just only swapped the order of width and height.

How do I keep this image in the center of the window?

I'm making a hangman-like game; for that, I need all the different stages of the man to be visualized, hence images. I want the entire tkinter window to be an image, when I change the size it pushes the image right.
from tkinter import *
root=Tk()
root.geometry("600x350")
canvas = Canvas(root, width=1600, height=900)
canvas.pack()
img = PhotoImage(file="4.png")
canvas.create_image(470,190, image=img, )
root.mainloop()
If canvas is bigger than window then when you resize then it show more canvas but and it can looks like it moves image.
But if you use smaller canvas then pack() will try to keep centered horizontally. And if you add pack(expand=True) then it will try to keep it centered vertically.
In example code I added red background to window to show where is canvas
import tkinter as tk # PEP8: import *
root = tk.Tk()
root.geometry("600x350")
root['bg'] = 'red'
img = tk.PhotoImage(file="lenna.png")
canvas = tk.Canvas(root, width=600, height=350)
canvas.pack(expand=True)
canvas.create_image(300, 175, image=img)
root.mainloop()
Image Lenna from Wikipedia
PEP 8 -- Style Guide for Python Code
Before resizing:
After resizing:
If you want to draw only image then you could use Label(image=img)
import tkinter as tk # PEP8: import *
root = tk.Tk()
root.geometry("600x350")
root['bg'] = 'red'
img = tk.PhotoImage(file="lenna.png")
label = tk.Label(root, image=img)
label.pack(expand=True)
root.mainloop()
Before resizing:
After resizing:
BTW:
tkinter can bind() some function to event <Configure> and it will execute this function everytime when you resize window (and/or move window) - and this function may also move or resize image in window.
import tkinter as tk # PEP8: import *
from PIL import Image, ImageTk
def resize(event):
global img
lower = min(event.width, event.height)
#print(event.width, event.height, 'lower:', lower)
new_image = original_image.resize((lower, lower))
img = ImageTk.PhotoImage(new_image) # need to assign to global variable because there is bug in PhotoImage
label['image'] = img
# --- main ---
root = tk.Tk()
root.geometry("350x350")
root['bg'] = 'red'
original_image = Image.open("lenna.png")
img = ImageTk.PhotoImage(original_image)
label = tk.Label(root, image=img)
label.pack(expand=True)
root.bind('<Configure>', resize)
root.mainloop()
Before (it resized image at start to fit window):
After (it resized image to fit window):

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

Dynamically resize two panels in tkinter

I have setup 2 panels in a frame as so:
frameA = Frame(master)
frameA.pack(side=LEFT, fill=BOTH, expand=YES)
frameB = Frame(master)
frameB.pack(side=RIGHT, fill=BOTH, expand=YES)
recale = 0.4
self.img = ImageTk.PhotoImage(img.resize((int(rescale*width), int(recale*height)), Image.ANTIALIAS)
self.panelA = Label(frameA, image=self.img)
self.pabelA.pack(side=LEFT, fill=BOTH, expand=YES)
self.panelB = Label(frameB, image=self.img)
self.pabelB.pack(side=LEFT, fill=BOTH, expand=YES)
Now, the size of the 2 panels are determined by the image size which I have resized to 0.4 times the original size. How can I dynamically set rescale such that the width of each of the panels takes up the entire width of the master frame when I press the maximize button(this is not a button I made, but rather the little square button next to minimize, and close on the top right) on the GUI?
When you use pack(fill=BOTH, expand=YES) then tkinter automatically resizes Frame and Label to fit window - so you don't have to resize it manually. But it will never resize PhotoImage and Image so it may looks like it doesn't resize Label and Frame. So your real problem probably is "how to resize Image when you change window's size"
Using
root.bind('<Configure>', on_resize)
you can run function when window changed size and then you can generate new image and replace in Label
This function will be executed not only for window but also fro every widget in window so I use str(event.widget) == '.' to resize it only when it is executed for window.
import tkinter as tk
from PIL import Image, ImageTk
def on_resize(event):
global rescaled_img
global photo
#print('[DEBUG] on_resize:', event.widget)
# resize only when root window changes size
if str(event.widget) == '.':
# generate new image
width = event.width//2 # -2 # -2*border
height = event.height # -2 # -2*border
rescaled_img = original_img.resize((width, height), Image.ANTIALIAS)
photo = ImageTk.PhotoImage(rescaled_img)
# replace images in labels
label_left['image'] = photo
label_right['image'] = photo
# ---- main ---
# resize at start
original_img = Image.open('image.jpg')
rescale = 0.4
width = int(rescale * original_img.width)
height = int(rescale * original_img.height)
rescaled_img = original_img.resize((width, height), Image.ANTIALIAS)
root = tk.Tk()
photo = ImageTk.PhotoImage(rescaled_img)
label_left = tk.Label(root, image=photo, border=0) # if border > 0 then you have to use `-2*border` in on_resize
label_left.pack(side='left', fill='both', expand=True)
label_right = tk.Label(root, image=photo, border=0) # if border > 0 then you have to use `-2*border` in on_resize
label_right.pack(side='left', fill='both', expand=True)
# resize when window changed size
root.bind('<Configure>', on_resize)
root.mainloop()
I tried to bind to label as you can see in some code in Tkinter resize background image to window size but it didn't work correctly - at start it makes images bigger and bigger till window fill all screen. Or at start it makes images small and small till window has no size.
if Label has border bigger then 0 then you have to substract 2*border from image size.

Categories