Jerome
Jerome

Reputation: 11

Stack overflow during a Tkinter Drag and Drop

This little piece of Python code implements a Drag and Drop feature in a Canvas BUT when you move an item without releasing it for too long (very quickly actually) a stack overflow occurs. Can someone explain why?

from tkinter import *

class Pawn():

    def __init__(self, canvas, x, y):
        self.canvas = canvas
        self.oval = canvas.create_oval(x-20, y-20, x+20, y+20, fill='black')
        canvas.tag_bind(self.oval, '<Button1-Motion>', self.move)

    def move(self, event):
        x1, y1, x2, y2 = event.x-20, event.y-20, event.x+20, event.y+20
        self.canvas.coords(self.oval, x1, y1, x2, y2)
        self.canvas.update()

class Application(Tk):

    def __init__(self, size):
        Tk.__init__(self)
        canvas = Canvas(self, height=size, width=size)
        canvas.pack(side=TOP)

        Pawn(canvas, 50, 50)
        Pawn(canvas, 100, 50)

Application(400).mainloop()

The error message:

Fatal Python error: Cannot recover from stack overflow. Current thread 0x000000011917bdc0 (most recent call first): File 
"/Users/attila/opt/miniconda3/lib/python3.7/tkinter/__init__.py", line 1704 in call File 
"/Users/attila/opt/miniconda3/lib/python3.7/tkinter/__init__.py", line 1177 in update File "/Users/attila/Desktop/dnd.py", line 21 in move `

Upvotes: 0

Views: 59

Answers (1)

Jerome
Jerome

Reputation: 11

Actually I have the answer to my question: it's useless and redundant to put a canvas.update after the canvas.coords. There is no more stack overflow without it. Sorry for the quick post. So the right code for the method move is just:

def move(self, event):
    x1, y1, x2, y2 = event.x-20, event.y-20, event.x+20, event.y+20
    self.canvas.coords(self.oval, x1, y1, x2, y2)

Upvotes: 1

Related Questions