使用python drag&删除所选图像片段

时间:2017-04-04 09:43:35

标签: python numpy image-processing matplotlib tkinter

我的要求是我需要将图像拖到所需的位置。  基于链接board-drawing code to move an oval 以下是我试过的代码快照。我没有得到任何错误。请让我知道如何推进它。

Sample image segment attached

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()

1 个答案:

答案 0 :(得分:0)

正如评论中所述:

  

缩进很重要!

在Example-class中,它的启动方法整个代码块未对齐:

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)

如果我只是在整个块的缩进中添加Tab,我就可以毫无问题地运行OP的代码。

由于脚本要求GIF文件放在images/test1.gif我已下载并使用此GIF:enter image description here

tkinter似乎并没有真正发挥gif(OP没有问过),但确实显示了它。