PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 6, 2022

[FIXED] How do I make a button with a function which rotates an image 180 Degrees?

 May 06, 2022     image, image-rotation, python     No comments   

Issue

How do I make a button with a function which rotates an image 180 degrees? The variable my image is stored in is

img = ImageTk.PhotoImage("spidey.png")

I have already imported the PIL library's ImageTk and Image. I also want to place my image in the middle of my root window.

from tkinter import *

from PIL import ImageTK, Image root=Tk()

root.title("Image Viewer")

root.geometry("550x650")

root.configure(background="black")

img = ImageTk.PhotoImage("spidey.png")

def rotate():

root.mainloop()
This is my code so far. Please help me out. Thanks.

I tried to write Img.rotate(180_degrees) but it didn't work. I expected it to work the first time but it didn't. So again, please help me out.


Solution

The rotation must be applied to the image after you call Image.open but before you call ImageTk.PhotoImage. The parameter passed to .rotate is just a number (representing degrees), so you'll also want Img.rotate(180) instead of Img.rotate(180_degrees).

import tkinter as tk
from PIL import ImageTk, Image

window = tk.Tk()
pic = Image.open("yourpic.png")
rotatedPic = pic.rotate(180)
finalPic = ImageTk.PhotoImage(rotatedPic)

label = tk.Label(master=window, image=finalImage)
label.place(x=0, y=0, width=200, height=200)

Note that you'll also need something to display the picture inside. You could use a canvas element and create_image, or (as in my example) use a widget with an image property and assign the rotated image to that property.

This was my source for the .rotate documentation: https://pythonexamples.org/python-pillow-rotate-image-90-180-270-degrees/



Answered By - Quack E. Duck
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing