I want to draw a box that will appear in a random place in the window. But it gives an error in line 33: name 'draw' is not defined . Tell me please, what am I doing wrong?

 import turtle import time import random class Rectangle: def __init__(self, x, y): self.x = x self.y = y def draw(self): self.color('black') self.penup() self.setpos(x, y) self.pendown() self.goto(x + 50, y) self.goto(x + 50, y + 50) self.goto(x, y + 50) self.goto(x, y) rect1 = Rectangle(random.randint(-200, 200), random.randint(-200, 200)) turtle.tracer(0, 0) turtle.hideturtle() rect1 = turtle.Turtle() rect1.hideturtle() while True: time.sleep(0.5) rect1.clear() draw(rect1) #ошибка turtle.update() 
  • probably had to be called as method rect1.draw() - slippyk
  • @slippyk, then we get an error: '' Turtle 'object has no attribute' draw '' in the same place - yashi
  • correctly, the code first rect1 = Rectangle , then the redefinition of rect1 = turtle.Turtle() , and draw(rect1) , this function is not described anywhere, there is only a class method Rectangle().draw() - slippyk
  • What is the logic in this code? - slippyk
  • @slippyk and then how to do it? - yashi

1 answer 1

 import turtle import random class Rectangle: def __init__(self, x, y): self.x = x self.y = y def draw(self, turtle): turtle.color('black') turtle.setpos(self.x, self.y) turtle.clear() turtle.goto(self.x + 50, self.y) turtle.goto(self.x + 50, self.y + 50) turtle.goto(self.x, self.y + 50) turtle.goto(self.x, self.y) turtle.Turtle() turtle.tracer(0, 0) turtle.hideturtle() rect1 = Rectangle(random.randint(-200, 200), random.randint(-200, 200)) rect1.draw(turtle) turtle.update() turtle.mainloop() 
  • I would def draw(self): -> def draw(self, turtle): well, rect1.draw() -> rect1.draw(turtle) - gil9red
  • @ gil9red corrected - slippyk