Python Forum
Drag and drop image object
Thread Rating:
  • 1 Vote(s) - 2 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Drag and drop image object
#1
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()
Reply
#2
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  GUI with drag and drop functionality sayyedkamran 7 6,028 May-26-2020, 10:20 PM
Last Post: jefsummers
  Looking for Python IDE With Drag and Drop GUI Dan_PanMan 0 2,292 May-23-2020, 04:39 PM
Last Post: Dan_PanMan
  [PyQt] Drag and Move window from menubar WBPYTHON 3 4,705 Apr-03-2020, 06:15 PM
Last Post: deanhystad
  click drag olivers 1 2,896 Jan-30-2020, 01:44 AM
Last Post: Larz60+
  [PyQt] Drag items across tabs Alfalfa 5 4,685 Sep-01-2019, 11:58 PM
Last Post: Alfalfa
  [Tkinter] Problem loading an image from directory into a Canvas object tiotony 3 3,776 Sep-02-2018, 06:47 PM
Last Post: woooee
  [PyQt] Drag and drop converter Raures 0 4,467 Oct-01-2017, 07:44 PM
Last Post: Raures
  Drag and Drop GUI crystallized_neuron 3 16,525 Apr-26-2017, 08:41 PM
Last Post: joe_anonimist

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020