Я отредактировал ваш код.
Вместо
self.canvas.bind("<space>", self.on_space_press)
Использовать
self.bind("<space>", self.on_space_press)
Я также добавилфункция сохранения в ваш код
def save_file(self):
# This will draw a rectangle on the image
self.draw.rectangle( self.rec_coords, outline=self.outline_color)
# Name of the file and format you want to save as
self.im.save("out_put.jpg","JPEG")
Полный код
import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk, ImageDraw
import sys
class ExampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.x = self.y = 0
self.canvas = tk.Canvas(self, width=512, height=720, cursor="cross", highlightthickness=0)
self.canvas.pack(side="top", fill="both", expand=True)
self.update()
self.canvas.bind("<ButtonPress-1>", self.on_button_press)
self.canvas.bind("<B1-Motion>", self.on_move_press)
self.canvas.bind("<ButtonRelease-1>", self.on_button_release)
self.rect = None
self.start_x = None
self.start_y = None
self.outline_color = "red"
self._draw_image()
# Space to destroy
self.bind("<space>", self.on_space_press)
def _draw_image(self):
self.im = Image.open('./EFCTupright_04203d903.jpg').resize((self.winfo_reqwidth(), self.winfo_reqheight()))
self.tk_im = ImageTk.PhotoImage(self.im)
self.draw = ImageDraw.Draw(self.im)
self.canvas.create_image(0,0,anchor="nw",image=self.tk_im)
# Destroy image:
def on_space_press(self, event):
self.save_file()
self.destroy()
def on_button_press(self, event):
# save mouse drag start position
self.start_x = event.x
self.start_y = event.y
# create rectangle if not yet exist
#if not self.rect:
self.rect = self.canvas.create_rectangle(self.x, self.y, 0, 0, outline=self.outline_color, tag="rect")
def on_move_press(self, event):
curX, curY = (event.x, event.y)
# expand rectangle as you drag the mouse
self.canvas.coords(self.rect, self.start_x, self.start_y, curX, curY)
def on_button_release(self, event):
pass
def save_file(self):
# This will draw a rectangle on the image
for rect in self.canvas.find_withtag("rect"):
self.draw.rectangle( self.canvas.coords(rect), outline=self.outline_color)
# Name of the file and format you want to save as
self.im.save("out_put.jpg","JPEG")
if __name__ == "__main__":
app = ExampleApp()
app.mainloop()