pythontkintermouseeventlinetkinter.checkbutton

draw a line between 2 checkbuttons chosen with mouse click in python


I have a code to paste checkbuttons in a canvas. They also change colors if clicked. If I click another checkbutton that is set up from the beginning, I want to be able to draw a line between 2 checkbuttons I select with the mouse click. Also I need the line to change the color when I click the first checkbutton. Any suggestion how to do it? line should be straight

    from tkinter import *

root = Tk()

buttons = []

class CMD: #Auxilliary function for callbacks using parameters. Syntax: CMD(function, argument1, argument2, ...)
    def __init__(s1, func, *args):
        s1.func = func
        s1.args = args
    def __call__(s1, *args):
        args = s1.args+args
        s1.func(*args)

 def color_checkbutton(pos=0):  # define the colors of the checkbutton
    if buttons[pos][0].get() == 1:
        buttons[pos][2].configure(bg='red')
    else:
        buttons[pos][2].configure(bg='green')

def place_checkbutton_in_canvas(e):  # order to insert the checkbutton
    if len(str(e.widget))<3: ## Don't place a new one if a checkbox was clicked
        b = IntVar()
        pos = len(buttons)
        xx_and = e.x
        yy_and = e.y
        buttons.append([b,pos, Checkbutton(root, variable=b, textvariable=b, command=CMD(color_checkbutton,pos))])
        buttons[-1][2].place(x=xx_and, y=yy_and)
        color_checkbutton(pos)

root.bind('<Button-1>', place_checkbutton_in_canvas)

line = IntVar()
draw_line_check = Checkbutton(root, variable=line)
draw_line_check.place(x=30,y=100)

root.mainloop()

Solution

  • You would need a lot more code and you are not even close in my opinion.

    Most importantly you dont have the checkbuttons IN your canvas, you have your Checkbuttons above the Canvas, if you dont use somewhere create_window in put them in(even though in your code isnt a canvas yet). But you will like to have them in the Canvas to use the bbox method of the canvas later.

    The next thing is how you try to save your data, with more checkbuttons it get more complex. May think about a defaultdict, or even better define a class(object) where you can target them easier and define class functions for the behavior.

    draw_line_check = Checkbutton(root, variable=line)
    

    The above line will need a command where you will bind your Button-1 to another behavior if clicked and vice versa.

    So I would do it like this:

    1. define a class that will place a Checkbutton on your Canvas and behave what ever you like.
    2. keep track of your instances somewhere in the global namespace with a defaultdict
    3. define a function that creates instances of your class.
    4. write a function that rebinds your Button-1