Click here to Skip to main content
15,911,360 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How to connect the line button with line function. The line function should work whenever the button is pressed.

What I have tried:

from tkinter import *
root =Tk()

# Width x Height
root.geometry("1366x768")
canvas_width = 1200
canvas_height = 500
w = canvas_width // 2
h = canvas_height // 2
my_canvas = Canvas(root, width=canvas_width, height=canvas_height, bg='light gray', scrollregion=(0, 0, 800, 1000))


# Create the button
b1 = Button(root, text="Line", bg="Red")
b1.pack()

# Cretae the line function
coords = {"x": 0, "y": 0, "x2": 0, "y2": 0}
final = []
lines = []


def click(e):
coords["x"] = e.x
coords["y"] = e.y
lines.append(my_canvas.create_line(coords["x"], coords["y"], coords["x"], coords["y"], fill='red', width=1))


def release(l):
lis = []
lis.append(coords["x"]);
lis.append(coords["y"]);
lis.append(coords["x2"]);
lis.append(coords["x2"])
final.append(lis)


def drag(e):
coords["x2"] = e.x
coords["y2"] = e.y
my_canvas.coords(lines[-1], coords["x"], coords["y"], coords["x2"], coords["y2"])

my_canvas.bind("<buttonpress-1>", click)
my_canvas.bind("<b1-motion>", drag)
my_canvas.bind('<buttonrelease-1>', release)
my_canvas.pack()



mainloop()
Posted
Updated 13-Dec-21 0:31am

1 solution

Your button definitions are incorrect, and should be as follows:
Python
my_canvas.bind("<Button-1>", click)
my_canvas.bind("<Motion>", drag)
my_canvas.bind('<ButtonRelease-1>', release)

Although the ButtonRelease does not seem to be actioned. See Understanding Tkinter Event Binding Clearly[^] for further help.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900