简体   繁体   中英

How do you create colored lines based on the length with Tkinter?

For a project I need to draw lines in Python and color them based on its length. For example, if the line's length is less than 25% of the length of the canvas, it should be green. I'm new to Python so I'm not exactly sure how to approach this. I already have the lines set up. They just need color. Any helpful links will help.

This is my code for the line.

    class putLine(object):
        def __init__(mouseClick, frame):
            mouseClick.frame = frame
            mouseClick.start_coords = None
            mouseClick.end_coords = None
        def __call__(mouseClick, event):
            coords = event.x, event.y
            if not mouseClick.start_coords:
                mouseClick.start_coords = coords
                return
            mouseClick.end_coords = coords
            mouseClick.frame.create_line(mouseClick.start_coords[0],
                                    mouseClick.start_coords[1],
                                    mouseClick.end_coords[0],
                                    mouseClick.end_coords[1])
            mouseClick.start_coords = mouseClick.end_coords

You can calculate the distance between the points, and set the color to red if the distance is more than 25% of the width.

from tkinter import *
from cmath import polar 



class Lines(Canvas):

    def __init__(self,master,**kwargs):

        super(Lines, self).__init__(**kwargs)
        self.bind( "<ButtonPress-1>", self.set_start_vector)
        self.bind("<ButtonRelease-1>", self.set_end_vector)           


    def set_start_vector(self, event):

        self.svx, self.svy = (event.x, event.y)


    def set_end_vector(self, event):

        self.evx, self.evy = (event.x, event.y)
        length = polar(complex(self.svx, self.svy)-complex(self.evx, self.evy))[0]

        if(length < self.winfo_width()*0.25):
            color = "green"
        else:
            color = "red"

        self.create_line(self.svx, self.svy, self.evx, self.evy, fill=color)



master = Tk()

w = Lines(master, 
           width=700, 
           height=400)
w.pack(expand = YES, fill = BOTH)

mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM