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.
CodePudding user response:
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
CodePudding user response:
you need to do following:
my_canvas.draw_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()