首页 > 解决方案 > Python - 如何为键绑定设置条件

问题描述

最近我在这里找到了这段代码(How to draw a line following your mouse coordinates with tkinter?):

import tkinter as tk

def draw(event):
    x, y = event.x, event.y
    if canvas.old_coords:
        x1, y1 = canvas.old_coords
        canvas.create_line(x, y, x1, y1)
    canvas.old_coords = x, y

def draw_line(event):

    if str(event.type) == 'ButtonPress':
        canvas.old_coords = event.x, event.y

    elif str(event.type) == 'ButtonRelease':
        x, y = event.x, event.y
        x1, y1 = canvas.old_coords
        canvas.create_line(x, y, x1, y1)

def reset_coords(event):
    canvas.old_coords = None

root = tk.Tk()

canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
canvas.old_coords = None

root.bind('<ButtonPress-1>', draw_line)
root.bind('<ButtonRelease-1>', draw_line)

#root.bind('<B1-Motion>', draw)
#root.bind('<ButtonRelease-1>', reset_coords)

root.mainloop()

我真的很好奇如何使这些功能相应地工作,例如选定的选项。比方说,我想在徒手绘制和绘制线条时进行选择。我尝试使用一个整数进行比较,然后定义绑定条件,如下所示:

if c==1:
    root.bind('<ButtonPress-1>', draw_line)
    root.bind('<ButtonRelease-1>', draw_line)
elif c==2:
    root.bind('<B1-Motion>', draw)
    root.bind('<ButtonRelease-1>', reset_coords)

但它似乎不起作用。你有任何想法如何为绑定创造条件吗?

标签: pythontkinterconditional-statements

解决方案


因此,如评论部分所述,我创建了一个函数,该函数合并了两个原始函数的操作,然后将所有使用的键符绑定到新函数


推荐阅读