首页 > 解决方案 > 将 2 个按钮与一条线连接在一起的按钮 (Tkinter)

问题描述

我又做了一个新的改变。现在,当我双击时,它有时会在按钮之间画线,但它似乎也没有按照我的预期工作。就像当我单击“添加行”按钮时我可以连接任何按钮一样,但它有点麻烦。有时它会记录我的双击,有时当我单击按钮 1 和 5 时,它会连接 2 和 3。那么我该怎么做呢,当我只双击按钮 2 和 3 时,它会连接按钮 2 和 3。

from tkinter import *
import tkinter

counter = 1
undone = []

numcount = 1

def drag_start(event):
    widget = event.widget
    widget.startX = event.x
    widget.startY = event.y

def drag_motion(event):
    global x, y
    widget = event.widget
    x = widget.winfo_x() - widget.startX + event.x
    y = widget.winfo_y() - widget.startY + event.y
    widget.place(x = x, y = y)

def add_button():
    global btn
    btn = Button(canvas, text = 'Button ' + str(numcount))  
    btn.pack(side = tkinter.TOP, anchor = tkinter.NW)
    btn.bind('<Button-1>', drag_start)
    btn.bind('<B1-Motion>', drag_motion)

def draw_line(event):
    global click_number
    global x1, y1
    if click_number == 0:
        x1 = x
        y1 = y
        click_number = 1
    else:
        x2 = x
        y2 = y
        canvas.create_line(x1, y1, x2, y2, width = 2, tag = 'line')
        click_number = 0

def add_line():
    btn.bind('<Double-Button-1>', draw_line)

def num():
    global numcount
    numcount += 1
    add_btn.config(text = 'Add Button')

def func(*funcs):
    def combined_func(*args, **kwargs):
        for f in funcs:
            f(*args, **kwargs)
    return combined_func

main = Tk()

main.title('Drag and Drop')
main.geometry('500x500')
canvas = Canvas(main, width = 500, height = 500, background = 'white')
canvas.pack(expand = YES, fill = BOTH)
click_number = 0

add_btn = Button(main, text = 'Add Button', command = func(add_button, num))
add_btn.place(x = 400, y = 10)

line_btn = Button(main, text = 'Add line', command = add_line)
line_btn.place(x = 400, y = 40)

main.mainloop()

标签: pythontkinter

解决方案


推荐阅读