How can you modify an image using tkinter scales? How can you modify an image using tkinter scales? tkinter tkinter

How can you modify an image using tkinter scales?


Ok, so I've been pouring over this for hours and I think I finally found a solution (you will need a .png file name picture.png in the same directory in order to run the below):

from tkinter import *from PIL import Image, ImageTkclass App(Frame):    def __init__(self, master):        Frame.__init__(self, master)        self.frame1 = Frame(self)        self.frame2 = Frame(self)        self.original = Image.open('picture.png')        self.image = ImageTk.PhotoImage(self.original)        self.display = Canvas(self.frame1)        self.xscale = Scale(self.frame2, from_=1, to=1000, orient=HORIZONTAL, command=self.resize)        self.yscale = Scale(self.frame2, from_=1, to=1000, orient=VERTICAL, command=self.resize)        self.display.pack(fill=BOTH, expand=1)        self.xscale.pack()        self.yscale.pack()        self.pack(fill=BOTH, expand=1)        self.frame1.pack(fill=BOTH, expand=1)        self.frame2.pack()        self.bind("<Configure>", self.resize)    def resize(self, *args):        size = (self.xscale.get(), self.yscale.get())        resized = self.original.resize(size,Image.ANTIALIAS)        self.image = ImageTk.PhotoImage(resized)        self.display.delete("IMG")        self.display.create_image(self.display.winfo_width()/2, self.display.winfo_height()/2, anchor=CENTER, image=self.image, tags="IMG")root = Tk()app = App(root)app.mainloop()

So what this does is create a canvas and two scales, whenever one of the scales is changed it will call the def resize which clears the items with tag IMG from the canvas and then draw a new image with width equal to the value of xscale and height equal to yscale with a tag of IMG. The creates the illusion of real time size updates as you drag the slider along the scales.

I could not, however, figure out a way to limit the scales upper values to the width of the canvas in pixels to prevent the user from expanding the image outside of the bounds of the canvas.

This could similarly be applied to allow you to live update whatever attributes of the image you needed to update with a slider value.