Answer the question
In order to leave comments, you need to log in
Drawing in Python on top of an image?
The task is this: open an image and draw a rectangle on it with the mouse , with the possibility of deletion and manipulation with coordinates.
Tkinter only works with GIF images.
PIL does not know how to draw with the mouse and it does not have the necessary widgets (button, label ect.)
PyGame is still more focused on the development of games and dynamic graphics, and I am only interested in geometric primitives.
Answer the question
In order to leave comments, you need to log in
Solution found. For anyone interested here is the code
import Tkinter as tk
from PIL import Image, ImageTk
class ExampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.x = self.y = 0
self.canvas = tk.Canvas(self, width=512, height=512, cursor="cross")
self.canvas.pack(side="top", fill="both", expand=True)
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._draw_image()
def _draw_image(self):
self.im = Image.open('1.jpg')
self.tk_im = ImageTk.PhotoImage(self.im)
self.canvas.create_image(0, 0, anchor="nw", image=self.tk_im)
def on_button_press(self, event):
# save mouse drag start position
self.start_x = event.x
self.start_y = event.y
#one rectangle
if not self.rect:
self.rect = self.canvas.create_rectangle(self.x, self.y, 1, 1, )
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
if __name__ == "__main__":
app = ExampleApp()
app.mainloop()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question