python - 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)
但它似乎不起作用。你有任何想法如何为绑定创造条件吗?
解决方案
因此,如评论部分所述,我创建了一个函数,该函数合并了两个原始函数的操作,然后将所有使用的键符绑定到新函数
推荐阅读
- php - WordPress中的自定义表单提交后未保存在数据库中并显示404错误
- csv - 使用管道 csv 删除行
- javascript - How to detect version of chrome used with puppeteer?
- windows - 如何强制 Kafka 在 64 位 JVM 上运行?
- service-worker - Web Share API 不适用于 Github 页面
- cygwin - 如何在我的电脑上编译这个 github 项目?
- php - 更改 SQL 模式或编辑查询?
- c# - 无法将字符串转换为 system.io
- python - 更新 tensorflow-gpu 后,为什么还要使用旧版本?
- wordpress - 致命错误:未捕获错误:调用未定义函数 mysql_error()