user4772964
user4772964

Reputation:

Tkinter: draw a point using a button click

I have a serious problem this morning: I load a picture to display it on a Canvas. The picture is large, so I set scroll bars to allow the user to view it.

I allow the user to press the right button in order to draw random points with his mouse on the image.

It works, but there is a bug in its behaviour: When I scroll to the right or down of the image and click the right mouse button the point is drawn but not on the pixel I clicked on. It is drawn far away and my brain does not understand why.

A second but less alarming problem is that the points are drawn only in black whatever the color I set to them.

Please help me to resolve this or tell me why this occur and I will try to do something about it. I have been fighting with this problem for 2 hours by now and I did not find similar issues on this website and the whole Google:

import PIL.Image
import Image
import ImageTk
from Tkinter import *        

class ExampleApp(Frame):
   def __init__(self,master):
        Frame.__init__(self,master=None)
        self.x = self.y = 0
        self.canvas = Canvas(self,  cursor="cross",width=600,height=650)

        self.sbarv=Scrollbar(self,orient=VERTICAL)
        self.sbarh=Scrollbar(self,orient=HORIZONTAL)
        self.sbarv.config(command=self.canvas.yview)
        self.sbarh.config(command=self.canvas.xview)

        self.canvas.config(yscrollcommand=self.sbarv.set)
        self.canvas.config(xscrollcommand=self.sbarh.set)

        self.canvas.grid(row=0,column=0,sticky=N+S+E+W)
        self.sbarv.grid(row=0,column=1,stick=N+S)
        self.sbarh.grid(row=1,column=0,sticky=E+W)

        self.canvas.bind("<ButtonPress-1>", self.on_button_press)

        self.rect = None

        self.start_x = None
        self.start_y = None

        self.im = PIL.Image.open("image.jpg")
        self.wazil,self.lard=self.im.size
        self.canvas.config(scrollregion=(0,0,self.wazil,self.lard))
        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):
       print"({}, {})".format(event.x,event.y)
       self.canvas.create_oval(event.x,event.y, event.x+1,event.y+1,fill='red')
       # the fill option never takes effect, I do not know why
       # When I scroll over the image, the pixels are not drawn where I click


if __name__ == "__main__":
    root=Tk()
    app = ExampleApp(root)
    app.pack()
    root.mainloop()

Thank you in advance for helping me.

Upvotes: 0

Views: 1530

Answers (1)

Eric Levieil
Eric Levieil

Reputation: 3574

1) You need to use canvasx and canvasy method. See for example: http://effbot.org/tkinterbook/canvas.htm#coordinate-systems

2) Your oval is so small you only see the border line. Use outline= instead of fill=

Upvotes: 2

Related Questions