Dynamic resizing rectangle on tkinter canvas

1.5k Views Asked by At

I am trying to create a simple slider that can resize a rectangle on the Tkinter canvas. I tried to first change the height only but it did not work.

from tkinter import *

sl_value = 10
def width(e):
    sl_value = e

root = Tk()
frame = Frame(root)
frame.pack()

slider = Scale(frame, from_=10 , to=100, orient = HORIZONTAL, bg="blue",command = width)
slider.pack()
canvas = Canvas(root,height=500,width=360)
canvas.pack()
rectangle = canvas.create_rectangle(20,50, 40,3*sl_value, fill="green")

root.mainloop()

It did not raise any errors either, just displays the initial state of the rectangle and the slider. What am I doing wrong here??

1

There are 1 best solutions below

0
gamesun On BEST ANSWER

Modify the function width() like this:

def width(e):
    x0, y0, x1, y1 = canvas.coords(rectangle) # get the coords of rect
    y1 = 3 * float(e)                         # calc new coords
    canvas.coords(rectangle, x0, y0, x1, y1)  # set new coords