Chris F Chris F - 2 years ago 107
Python Question

Change the width of a rectangle in tkinter's canvas widget

I've tried several ways to change the width of the blue rectangle in this example code. Nothing seems to work. In the code, "a" represents a float variable between 1.00, and 0.00. That value is used to calculate "b," which is the desired width of the blue rectangle in pixels. I have some fairly complicated code that generates that value, and at least that works. In order for the code to work, the width of the blue rectangle must rely on "b." I've tried "Canvas.itemconfig()," and it didn't work.

import tkinter
from tkinter import *

root = Tk()

root.maxsize(320,240) # Sets max size of window

canvas_height = 23
canvas_width = 315

w = Canvas(root, width=canvas_width, height=canvas_height)
w.create_rectangle(5, canvas_height, canvas_width, 2, fill="yellow")
w.create_rectangle(5, canvas_height, canvas_width, 2, fill="blue")

a = 1.0 # More complicated code creates this float between 0.00 and 1.00. It is a percentage of the desired 'blue rectangle' width
b = int(a * canvas_width)


If anyone could help, I would greatly appreciate it!

P.s. I'm new to the Stackoverflow community, so please let me know if there's anything I can do to make my questions easier to answer.

Answer Source

The rectangle is defined by a couple of coordinates for opposite corners. Get the coordinates of the left edge, add the width to the x coordinate, and use that to set the coordinates of the right edge.

First, keep track of the object id so you can change it later:

blue = w.create_rectangle(5, canvas_height, canvas_width, 2, fill="blue")

To resize, get the coordinates...

x0, y0, x1, y1 = w.coords(blue)

Do some math...

x1 = x0 + b

And reset the coordinates

w.coords(blue, x0, y0, x1, y1)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download