draw box with mouse on image in canvas tkinter

Solutions on MaxInterview for draw box with mouse on image in canvas tkinter by the best coders in the world

showing results for - "draw box with mouse on image in canvas tkinter"
Samuel
23 Nov 2020
1import PIL.Image
2import Image
3import ImageTk
4from Tkinter import *    
5
6
7class ExampleApp(Frame):
8    def __init__(self,master):
9        Frame.__init__(self,master=None)
10        self.x = self.y = 0
11        self.canvas = Canvas(self,  cursor="cross")
12
13        self.sbarv=Scrollbar(self,orient=VERTICAL)
14        self.sbarh=Scrollbar(self,orient=HORIZONTAL)
15        self.sbarv.config(command=self.canvas.yview)
16        self.sbarh.config(command=self.canvas.xview)
17
18        self.canvas.config(yscrollcommand=self.sbarv.set)
19        self.canvas.config(xscrollcommand=self.sbarh.set)
20
21        self.canvas.grid(row=0,column=0,sticky=N+S+E+W)
22        self.sbarv.grid(row=0,column=1,stick=N+S)
23        self.sbarh.grid(row=1,column=0,sticky=E+W)
24
25        self.canvas.bind("<ButtonPress-1>", self.on_button_press)
26        self.canvas.bind("<B1-Motion>", self.on_move_press)
27        self.canvas.bind("<ButtonRelease-1>", self.on_button_release)
28
29        self.rect = None
30
31        self.start_x = None
32        self.start_y = None
33
34        self.im = PIL.Image.open("logo.png")
35        self.wazil,self.lard=self.im.size
36        self.canvas.config(scrollregion=(0,0,self.wazil,self.lard))
37        self.tk_im = ImageTk.PhotoImage(self.im)
38        self.canvas.create_image(0,0,anchor="nw",image=self.tk_im)   
39
40
41    def on_button_press(self, event):
42        # save mouse drag start position
43        self.start_x = self.canvas.canvasx(event.x)
44        self.start_y = self.canvas.canvasy(event.y)
45
46        # create rectangle if not yet exist
47        if not self.rect:
48            self.rect = self.canvas.create_rectangle(self.x, self.y, 1, 1, outline='red')
49
50    def on_move_press(self, event):
51        curX = self.canvas.canvasx(event.x)
52        curY = self.canvas.canvasy(event.y)
53
54        w, h = self.canvas.winfo_width(), self.canvas.winfo_height()
55        if event.x > 0.9*w:
56            self.canvas.xview_scroll(1, 'units') 
57        elif event.x < 0.1*w:
58            self.canvas.xview_scroll(-1, 'units')
59        if event.y > 0.9*h:
60            self.canvas.yview_scroll(1, 'units') 
61        elif event.y < 0.1*h:
62            self.canvas.yview_scroll(-1, 'units')
63
64        # expand rectangle as you drag the mouse
65        self.canvas.coords(self.rect, self.start_x, self.start_y, curX, curY)    
66
67    def on_button_release(self, event):
68        pass    
69
70if __name__ == "__main__":
71    root=Tk()
72    app = ExampleApp(root)
73    app.pack()
74    root.mainloop()
75