create a visual program where you can drag/drop pictures around on the screen in python

You can create a visual program where you can drag and drop pictures around on the screen using GUI library Tkinter in Python.

Here is an example code that allows you to drag and drop a picture on a canvas using Tkinter:

main.py
from tkinter import *
from PIL import ImageTk, Image

class DragAndDrop(Frame):
    def __init__(self, parent):
        self.parent = parent
        self.parent.title("Drag and Drop")

        Frame.__init__(self, parent)

        self.create_widgets()
        self.grid(sticky = ALL)

    def create_widgets(self):
        self.canvas = Canvas(self, width=500, height=500)
        self.canvas.pack(fill=BOTH, expand=YES)

        self.img = Image.open("picture.png")
        self.photo = ImageTk.PhotoImage(self.img)
        self.canvas.create_image(0, 0, image=self.photo, anchor=NW, tags="icon")

        self.canvas.tag_bind("icon", "<ButtonPress-1>", self.on_button_press)
        self.canvas.tag_bind("icon", "<ButtonRelease-1>", self.on_button_release)
        self.canvas.tag_bind("icon", "<B1-Motion>", self.on_move)

        self.rect = None

    def on_button_press(self, event):
        self.rect = self.canvas.create_rectangle(event.x, event.y, event.x+1, event.y+1, outline='red')

    def on_button_release(self, event):
        self.canvas.delete(self.rect)
        self.rect = None

    def on_move(self, event):
        if self.rect:
            self.canvas.coords(self.rect, event.x, event.y, event.x+50, event.y+50)

if __name__ == "__main__":
    root = Tk()
    DragAndDrop(root)
    root.mainloop()
1322 chars
43 lines

In the above code, we create a class DragAndDrop which is inherited from Tkinter's Frame class.

We create a canvas widget and add an image to it using the create_image method. We bind three events to the image tag: <ButtonPress-1> for mouse left button press, <ButtonRelease-1> for mouse left button release, and <B1-Motion> for mouse motion.

When the <ButtonPress-1> event is triggered, we create a rectangle around the image. When the <ButtonRelease-1> event is triggered, we delete the rectangle. When the <B1-Motion> event is triggered, we move the rectangle with the mouse cursor.

Run this python code, it will create a window with an image. You can drag and drop the image around by clicking the left mouse button on the image, hold the click button and move the mouse.

related categories

gistlibby LogSnag