1

I have created an image on a canvas in tkinter that responds to a button event. And, the object is created on position x and position y where that event took place. But the object changes shape constantly.

def leftclick(event):

        canvas1=Canvas(play, height=hei, width=wid)
        canvas1.grid(row=0, column=0, sticky=W)
        canvas1.delete("all")


        x=event.x
        y=event.y
        print(event.x, event.y)



        bullet = canvas1.create_oval(x,y, 100,100, fill="red")
        xspeed=random.randint(0, 50)
        yspeed=random.randint(0,50)

This just draws ovals which are randomly shaped. Why is this happening and how do I fix it?

Luke B
  • 2,075
  • 2
  • 18
  • 26
TP123
  • 21
  • 5
  • Why are you creating a new canvas on each click? What is `play`? – chepner Oct 21 '19 at 21:16
  • I am creating a canvas, so the oval can be shown onto this canvas. play is the name of the tkinter window – TP123 Oct 21 '19 at 21:19
  • @TP123: You have to do **once**: `canvas1=Canvas(...` and `.create_oval(...`. Remove it from `def leftclick(...` and replace with `canvas1=event.widget`. The replacement of `.create_oval(...` depends at what you want to do with the `oval`? – stovfl Oct 21 '19 at 21:47
  • Please create a [mcve] that reproduces your problem. I don't think it's possible for the code you posted to cause the oval to change size or position. – Bryan Oakley Oct 21 '19 at 23:09

1 Answers1

0

You should only create your canvas once, but that's not a problem. The problem is that the tkinter tries to create an oval inside the rectangle. You've specified the 2 points of the rectangle: x,y and 100,100. Just use bullet = canvas1.create_oval(x-50,y-50, x+50,y+50, fill="red") or whatever number you pick instead of 50. Hope that's helpful!

rizerphe
  • 1,340
  • 1
  • 14
  • 24