Python Forum

Full Version: Drag and drop image object
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The following is the code to display an image and am trying to drag it to desired location. Once i click on the image the relavnt event method is not getting called and there is no error message displayed. please look into the issue
 import Tkinter as tk
from Tkinter import *
from PIL import ImageTk, Image

class Example(tk.Frame):

    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        # create a canvas
        self.canvas = tk.Canvas(width=400, height=400)
        self.canvas.pack(fill="both", expand=True)

        # this data is used to keep track of an 
        # item being dragged

        self._drag_data1 = {"x": 0, "y": 0, "item1": None}

    
    startframe = tk.Frame(root)
        canvas = tk.Canvas(startframe,width=1280,height=720)
    startframe.pack()
        canvas.pack()
    one = tk.PhotoImage(file=r'images/test1.gif')
        root.one = one  # to prevent the image garbage collected.
        canvas.create_image((0,0), image=one, anchor='nw',tags="img1")

    self.canvas.tag_bind("img1", "<1>", self.on_token_press1)
     self.canvas.tag_bind("img1", "<1>", self.on_token_release1)
        self.canvas.tag_bind("token", "<B1-Motion>", self.on_token_motion1)

   

    def on_token_press1(self, event):
    print("sss")
        # record the item and its location
        self._drag_data1["item1"] = self.canvas.find_closest(event.x, event.y)[0]
        self._drag_data1["x"] = event.x
        self._drag_data1["y"] = event.y

    def on_token_release1(self, event):

        # reset the drag information
        self._drag_data1["item1"] = None
        self._drag_data1["x"] = 0
        self._drag_data1["y"] = 0

    def on_token_motion1(self, event):
        '''Handle dragging of an object'''
        # compute how much the mouse has moved
        delta_x = event.x - self._drag_data1["x"]
        delta_y = event.y - self._drag_data1["y"]
        # move the object the appropriate amount
        self.canvas.move(self._drag_data1["item1"], delta_x, delta_y)
        # record the new position
        self._drag_data1["x"] = event.x
        self._drag_data1["y"] = event.y


if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()
Hi vijaysagi

Here one solution to drag, move and drop canvas image objects:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

try:
    # Tkinter for Python 2.xx
    import Tkinter as tk
except ImportError:
    # Tkinter for Python 3.xx
    import tkinter as tk

APP_TITLE = "Drag & Drop Tk Canvas Images"
APP_XPOS = 100
APP_YPOS = 100
APP_WIDTH = 300
APP_HEIGHT = 200

IMAGE_PATH = "images/"

class CreateCanvasObject(object):
    def __init__(self, canvas, image_name, xpos, ypos):
        self.canvas = canvas
        self.image_name = image_name
        self.xpos, self.ypos = xpos, ypos

        self.tk_image = tk.PhotoImage(
            file="{}{}".format(IMAGE_PATH, image_name))
        self.image_obj= canvas.create_image(
            xpos, ypos, image=self.tk_image)
        
        canvas.tag_bind(self.image_obj, '<Button1-Motion>', self.move)
        canvas.tag_bind(self.image_obj, '<ButtonRelease-1>', self.release)
        self.move_flag = False
        
    def move(self, event):
        if self.move_flag:
            new_xpos, new_ypos = event.x, event.y
            
            self.canvas.move(self.image_obj,
                new_xpos-self.mouse_xpos ,new_ypos-self.mouse_ypos)
            
            self.mouse_xpos = new_xpos
            self.mouse_ypos = new_ypos
        else:
            self.move_flag = True
            self.canvas.tag_raise(self.image_obj)
            self.mouse_xpos = event.x
            self.mouse_ypos = event.y

    def release(self, event):
        self.move_flag = False
                    
class Application(tk.Frame):

    def __init__(self, master):
        self.master = master
        self.master.protocol("WM_DELETE_WINDOW", self.close)
        tk.Frame.__init__(self, master)

        self.canvas = tk.Canvas(self, width=400, height=400, bg='steelblue',
            highlightthickness=0)
        self.canvas.pack(fill="both", expand=True)
        
        self.image_1 = CreateCanvasObject(self.canvas, "test1.gif", 100, 100)
        self.image_2 =CreateCanvasObject(self.canvas, "test1.gif", 200, 100)
            
    def close(self):
        print("Application-Shutdown")
        self.master.destroy()
    
def main():
    app_win = tk.Tk()
    app_win.title(APP_TITLE)
    app_win.geometry("+{}+{}".format(APP_XPOS, APP_YPOS))
    #app_win.geometry("{}x{}".format(APP_WIDTH, APP_HEIGHT))
    
    app = Application(app_win).pack(fill='both', expand=True)
    
    app_win.mainloop()
 
 
if __name__ == '__main__':
    main()      
wuf Smile