I want the cursor's x and y coordinates to be tracked by two sliding lines when the cursor is over a canvas. One on the top of the canvas constrained to x, and one at the left of the canvas constrained to y.
I have actually achieved this, almost:
import tkinter as tk
def callback(event):
draw_y_marker(event.y)
draw_x_marker(event.x)
def draw_x_marker(x):
paint.coords(line, x, 0, x, 20)
def draw_y_marker(y):
paint.coords(line, 0, y, 20, y)
root = Tk()
paint = Canvas(root)
paint.bind('<Motion>', callback)
paint.pack()
line = paint.create_line(x, 0, x, height)
root.mainloop()
If I comment out the draw_y_marker call in callback I get a the line constrained to x sliding along the top of the screen, marking cursor position. If I comment out draw_x_marker I get the line constrained to y sliding along the side of the screen.
But not both which is what I want! If I uncomment both, only the draw_x_marker method works. How can I paint two things on the canvas simultaneously?
CodePudding user response:
You have only created one line item in the canvas, so how can you show two sliding lines?
You need to create the two sliding lines for x and y and update them in callback()
:
import tkinter as tk
def callback(event):
draw_y_marker(event.y)
draw_x_marker(event.x)
def draw_x_marker(x):
paint.coords(xline, x, 0, x, 20)
def draw_y_marker(y):
paint.coords(yline, 0, y, 20, y)
root = tk.Tk()
paint = tk.Canvas(root)
paint.bind('<Motion>', callback)
paint.pack()
# create the two sliding lines initially
xline = paint.create_line(0, 0, 0, 0)
yline = paint.create_line(0, 0, 0, 0)
root.mainloop()