I have some code that repeats that I would like to compress into a loop somehow. The code is meant to show a series of rectangles that change color when your mouse hovers over them, and because I have numerous rectangles, all of the code repeating is the same except for 2 coordinates for the location of my rectangles. Therefore, I want to somehow compress the following code into a loop:
from tkinter import *
c=Canvas(width=800, height=600, bg="White")
c.create_rectangle(50,50,70,150,outline="Blue",
width=2,fill="Gray",activefill="Red")
c.create_rectangle(90,50,110,150,outline="Blue",
width=2,fill="Gray",activefill="Red")
c.create_rectangle(130,50,150,150,outline="Blue",
width=2,fill="Gray",activefill="Red")
c.create_rectangle(170,50,190,150,outline="Blue",
width=2,fill="Gray",activefill="Red")
c.create_rectangle(210,50,230,150,outline="Blue",
width=2,fill="Gray",activefill="Red")
c.create_rectangle(250,50,270,150,outline="Blue",
width=2,fill="Gray",activefill="Red")
c.create_rectangle(290,50,310,150,outline="Blue",
width=2,fill="Gray",activefill="Red")
c.create_rectangle(330,50,350,150,outline="Blue",
width=2,fill="Gray",activefill="Red")
c.create_rectangle(370,50,390,150,outline="Blue",
width=2,fill="Gray",activefill="Red")
c.create_rectangle(410,50,430,150,outline="Blue",
width=2,fill="Gray",activefill="Red")
c.create_rectangle(450,50,470,150,outline="Blue",
width=2,fill="Gray",activefill="Red")
c.create_rectangle(490,50,510,150,outline="Blue",
width=2,fill="Gray",activefill="Red")
c.pack()
mainloop()
My first idea to approaching this was setting the original rectangle dimensions to (x, 50, y, 150), setting x=50 and y=70, and then somehow incorporating that while x<=490 and y<=510, x=x+40. However, I don’t know how to incorporate all of this into a loop.
>Solution :
This is the alteration you are looking for using a while loop:
from tkinter import *
c = Canvas(width=800, height=600, bg="White")
cords = [50, 50, 70, 150]
while cords[0] <= 490 and cords[2] <= 510:
c.create_rectangle(cords, outline="Blue", width=2, fill="Gray", activefill="Red")
cords[0] += 40
cords[2] += 40
c.pack()
mainloop()