9

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
root.minsize(320,240)

canvas_height = 23
canvas_width = 315

w = Canvas(root, width=canvas_width, height=canvas_height)
w.pack()
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)

root.mainloop() 

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.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
Chris F
  • 101
  • 1
  • 1
  • 6
  • What exactly does "it didn't work" mean? Did you get an error message? What was the intended outcome, and what was the actual outcome? – Håken Lid Nov 23 '16 at 19:34
  • The articles [ask] and [mcve] contain tips on how to solve bugs and how to ask for help – Håken Lid Nov 23 '16 at 19:34

1 Answers1

16

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)
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • I have one follow up question. Firstly, what you gave me worked. I made a loop, that counts down in seconds. After counting 1 second, it calls "DownButton", which calculates "c" (c = c / 100). Then, DownButton() calls Change(), which calculates "a", the percentage of the width, and finally, using your code, updated the blue rectangle. However, blue only updates when the timer is done. If i remove Timer(), and use tkinter Buttons to call UpButton() and DownButton(), it works just fine. Thanks for the answer, and if you have a min, could you help me figure this one out? :) – Chris F Nov 23 '16 at 20:46
  • @ChrisF: the screen is updated whenever the event loop gets a chance to service events. There are many questions and answers on this site related to that. – Bryan Oakley Nov 23 '16 at 20:50