1

I'm creating 2D game and when i am trying to add more than one wall they doesn't appear on canvas.

import tkinter

root = tkinter.Tk()
canvas = tkinter.Canvas(root)
canvas.pack()

class wall:
  point1 = []
  point2 = []
  def __init__(self, canvas, x1, y1, x2, y2):
    self.canvas = canvas
    self.point1.append(x1)
    self.point1.append(y1)
    self.point2.append(x2)
    self.point2.append(y2)
  def draw(self):
    self.canvas.create_line(self.point1[0], self.point1[1], self.point2[0], self.point2[1], width = 2)

walls = []
walls.append(wall(canvas, 90, 90, 100, 200))
walls.append(wall(canvas, 90, 90, 300, 100))

def update():
    for wall in walls:
        wall.draw()
    root.after(int(1000/60), update)
root.after(int(1000/60), update)
root.mainloop()

If I add them manually they are drawing both.

canvas.create_line(90, 90, 100, 200, width = 2)
canvas.create_line(90, 90, 300, 100, width = 2)
1
  • couldn't be easier to keep it as self.x1, self.y1, self.x2, self.y2 ? Commented Jul 27, 2019 at 7:03

2 Answers 2

2

Consider this part of your class wall:

class wall:
    point1 = []
    point2 = []
    ...

The lists point1 and point2 are defined as class attribute instead of instance attribute. So when you append new coordinates, the previous ones are still there.

To fix this, simply make point and point2 instance attributes instead:

class wall:

    def __init__(self, canvas, x1, y1, x2, y2):
        self.point1 = []
        self.point2 = []
        ...

Or use the parameters directly:

class wall:
    def __init__(self, canvas, x1, y1, x2, y2):
        self.canvas = canvas
        self.x1 = x1
        self.y1 = y1
        self.x2 = x2
        self.y2 = y2
    def draw(self):
       self.canvas.create_line(self.x1, self.y1, self.x2, self.y2, width = 2)
Sign up to request clarification or add additional context in comments.

Comments

-1

Use Instance attributes instead of Class attributes.

 class wall:
      def __init__(self, canvas, x1, y1, x2, y2):
        self.canvas = canvas
        self.x1 = x1
        self.y1 = y1
        self.x2 = x2
        self.y2 = y2
      def draw(self):
        self.canvas.create_line(self.x1, self.y1, self.x2, self.y2, width=2)

1 Comment

describe it. Code without explanation is less useful - even if it can be good idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.