4

I was just wondering, is there any way in tkinter in python to resize/rescale a picture with the mouse (similar to how you can rescale images in google docs)? The code I have so far:

def addImage(self, docx):
    filename = filedialog.askopenfile(title="Select a file")
    myImage = ImageTk.PhotoImage(Image.open(filename.name))
    position = docx.index(INSERT)
    docx.image_create(position, image=myImage)
    docx.photo = myImage

    # here I want to be able to resize the image I have put in my document with the mouse

Thanks in advance

1
  • 1
    Possible, yes, but difficult. Not for a beginner programmer. You would need to make a custom widget that displayed the handles and reacted to them. Commented Feb 7, 2021 at 21:45

1 Answer 1

2

I have tried this

from tkinter import *
from PIL import Image,ImageTk

class Resizable:
    def __init__(self,label,image):
        self.label=label
        self.image=image
        self.label.master.bind('<Motion>',self.position)        
        self.flag=False 

    def position(self,event):
        self.dimentions=(self.label.winfo_width(),self.label.winfo_height())
        self.x,self.y = event.x,event.y
        if (
            self.x in range (self.dimentions[0]-5,self.dimentions[0],1) and 
            self.y in range (self.dimentions[1]-5,self.dimentions[1],1)
        ):
            self.label.config(cursor='sizing')
            self.label.master.bind('<ButtonRelease-1>',self.end)
            self.label.bind('<Button-1>',self.start)
        else:
            self.label.config(cursor='')    
            self.label.unbind('<Button-1>')

    def end(self,event):
        self.flag=True
        self.label.master.unbind('<ButtonRelease-1>')

    def start(self,event):
        self.flag=False
        self.resize()

    def resize(self):
        if not self.flag:
            self.label.config(cursor='sizing')
            try:
                self.photoimage=ImageTk.PhotoImage(self.image.resize((self.x,self.y),Image.ANTIALIAS))
            except:
                pass
            self.label.config(image=self.photoimage)
            self.label.update()
            self.label.after(1,self.resize)

root=Tk()
root.geometry('400x300')

img_label=Label(bd=0)
img_label.pack()
image=Image.open('sample.png')
photoimage=ImageTk.PhotoImage(image.resize((100,100),Image.ANTIALIAS))
img_label.config(image=photoimage)
Resizable(img_label,image)

root.mainloop()

I believe you have a different way of inserting your image, but you can modify and improve this approach as per your requirement.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.