starkshang
starkshang

Reputation: 8528

How can I draw a point with Canvas in Tkinter?

I want to draw a point in Tkinter,Now I'm using Canvas to make it,but I didn't find such method to draw a point in Canvas class.Canvas provides a method called crete_line(x1,y1,x2,y2),so i tried to set x1=x2,y1=y2 to draw a point, but it doesn't work.

So anyone can tell me how to make it,it will be better if use Canvas can make it,other solution will be also accepted.Thanks!

Upvotes: 9

Views: 35903

Answers (4)

WIP
WIP

Reputation: 456

Since an update of the Tk lib (somewhere between Tk 8.6.0 and 8.6.9) the behavior of create_line had changed. To create a one pixel dot at (x, y) in 8.6.0 you add to write

canvas.create_line(x, y, x+1, y, fill=color)

Now on 8.6.9 you have to use:

canvas.create_line(x, y, x, y, fill=color)

Note that Debian 9 use 8.6.0 and Archlinux (in early 2019) use 8.6.9 so portability is compromised for a few years.

Upvotes: 2

ChaosPredictor
ChaosPredictor

Reputation: 4051

With create_line you have other possible workaround solution:

canvas.create_line(x, y, x+1, y, fill="#ff0000")

It overwrites only a single pixel (x,y to red)

Upvotes: 4

user223850
user223850

Reputation: 51

The provided above solution doesn't seem to work for me when I'm trying to put a sequence of a few pixels in a row.

I've found another solution -- reducing the border width of the oval to 0:

canvas.create_oval(x, y, x, y, width = 0, fill = 'white')

Upvotes: 5

trahane
trahane

Reputation: 721

There is no method to directly put a point on Canvas. The method below shows points using create_oval method.

Try this:

from Tkinter import *

canvas_width = 500
canvas_height = 150


def paint(event):
    python_green = "#476042"
    x1, y1 = (event.x - 1), (event.y - 1)
    x2, y2 = (event.x + 1), (event.y + 1)
    w.create_oval(x1, y1, x2, y2, fill=python_green)



master = Tk()
master.title("Points")
w = Canvas(master,
           width=canvas_width,
           height=canvas_height)
w.pack(expand=YES, fill=BOTH)
w.bind("<B1-Motion>", paint)

message = Label(master, text="Press and Drag the mouse to draw")
message.pack(side=BOTTOM)

mainloop()

Upvotes: 6

Related Questions