0

So, I have to write a code in python that will draw four squares under a function called draw_square that will take four arguments: the canvas on which the square will be drawn, the color of the square, the side length of the square, and the position of the center of the square. This function should draw the square and return the handle of the square. The create_rectangle method should only be used inside the draw_square function. This is what I have so far:

from tkinter import*

root = Tk()

my_canvas = Canvas(root, width=900, height=900, bg="white")
my_canvas.pack(pady=30)


def draw_square():

    draw_square.create_rectangle(0, 0, 150, 150, fill = "orange", 
    outline = "orange")
    draw_square.create_rectangle(750, 0, 900, 150, fill = "green", 
    outline = "green")
    draw_square.create_rectangle(0, 750, 150, 900, fill = "blue", 
    outline = "blue")
    draw_square.create_rectangle(750, 750, 900, 900, fill = "black", 
    outline = "black")

draw_square()

Please let me know what to do so my code can work.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
Rookie
  • 1
  • The description of the question is a bit confusing. Do you need a function to draw 4 squares inside that function, or a function to draw one square at a time and call that function 4 times to draw 4 squares? – acw1668 Nov 16 '21 at 00:40
  • I need to draw 4 squares inside that function – Rookie Nov 17 '21 at 00:56
  • Then how do you give the radii for the fourth argument in the requirement you state: *"a function called draw_square that will take four arguments: the canvas on which the square will be drawn, the color of the square, the side length of the square, and the position of the center of the square"*? My understanding based on this requirement is to create a function with four arguments to draw single rectangle. – acw1668 Nov 17 '21 at 01:05

2 Answers2

1

Use my_canvas.create_rectangle(...).

You were calling a draw rectangle from your function rather than the canvas itself.

Extra info: Tkinter Canvas creating rectangle

Larry the Llama
  • 958
  • 3
  • 13
0

you need to do following:

my_canvas.create_rectangle(...)

my_canvas.pack()

...

...

after you finish for all 4 squares drawing and packing you need to call function like following:

draw_square()

root.mainloop()

Thyrus
  • 458
  • 2
  • 13