在 python 中用鼠标单击选择的 2 个复选按钮之间画一条线

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

我有一个代码可以在 canvas 中粘贴复选按钮。如果单击它们也会改变颜色。如果我单击从一开始就设置的另一个复选按钮,我希望能够通过单击鼠标在 select 的 2 个复选按钮之间画一条线。当我点击第一个复选按钮时,我还需要改变颜色的线条。任何建议如何去做?

    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()

你需要更多的代码,我认为你还差得远。

最重要的是你没有 IN 你的 canvas,你有上面的 Canvas,如果你不使用某处 create_window 将它们放入(即使在你的代码中还不是 canvas)。但是您希望将它们放在 Canvas 中以便稍后使用 canvas 的

接下来是您尝试保存数据的方式,复选按钮越多,事情就越复杂。可以考虑 defaultdict,甚至更好地定义 class(object),您可以更轻松地定位它们并为行为定义 class 函数。

draw_line_check = Checkbutton(root, variable=line)

以上行需要一个命令,您可以在该命令中将 Button-1 绑定到另一个行为(如果单击则反之亦然)。

所以我会这样做:

  1. 定义一个 class,它将在您的 Canvas 上放置一个 Checkbutton,并按您喜欢的方式运行。
  2. 使用 defaultdict
  3. 在全局命名空间的某处跟踪您的实例
  4. 定义一个函数来创建 class.
  5. 的实例
  6. 写一个函数重新绑定你的 Button-1