【问题标题】:draw a line between 2 checkbuttons chosen with mouse click in python在 python 中通过鼠标单击选择的 2 个复选按钮之间画一条线
【发布时间】:2020-08-19 14:49:20
【问题描述】:

我有一个在画布中粘贴复选按钮的代码。如果单击,它们也会改变颜色。如果我单击从一开始就设置的另一个检查按钮,我希望能够在我通过鼠标单击选择的 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()

【问题讨论】:

    标签: python tkinter mouseevent line tkinter.checkbutton


    【解决方案1】:

    你需要更多的代码,在我看来你甚至还不够接近。

    最重要的是,您的 canvas 没有检查按钮 IN,如果您不在某个地方使用 @987654323,则您的检查按钮 高于 Canvas @ in 把它们放进去(即使在你的代码中还不是画布)。但是您希望将它们放在 Canvas 中,以便稍后使用画布的 bbox method。

    接下来是您如何尝试保存数据,检查按钮越多就越复杂。可以考虑defaultdict,或者更好地定义class(object),您可以在其中更轻松地定位它们并为行为定义类函数。

    draw_line_check = Checkbutton(root, variable=line)
    

    上面的行需要一个命令,如果单击,您会将Button-1 绑定到另一个行为,反之亦然。

    所以我会这样做:

    1. 定义一个类,该类将在您的 Canvas 上放置一个 Checkbutton 并按照您的喜好行事。
    2. 使用 defaultdict 在全局命名空间中的某处跟踪您的实例
    3. 定义一个创建类实例的函数。
    4. 编写一个函数来重新绑定你的Button-1

    【讨论】:

      猜你喜欢
      • 2020-03-01
      • 2012-01-12
      • 2012-08-28
      • 2015-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-05
      • 1970-01-01
      相关资源
      最近更新 更多