python - 如何通过“绘画”来触发按钮?使用 tkinter 的“B1-Motion”?
问题描述
我想制作一个按钮,如果您单击并拖动它(“绘制”它???),它将被触发。这是我的尝试:
import tkinter as tk
class PaintOverWidget():
def __init__(self, master):
b = tk.Button(master, text="UnMark All",command=self.clicked)
b.bind("<B1-Motion>", self.pressed)
b.pack()
def clicked(self):
print('clicked')
def pressed(*e):
print ('painted')
root=tk.Tk()
my_gui = PaintOverWidget(root)
root.mainloop()
运行时,它成功报告单击,但如果我单击窗口中的其他位置并拖动按钮,它无法报告它已被“绘制”。
出了什么问题,我该如何解决?
解决方案
问题:使用 tkinter 的事件
Button
通过“绘画”触发 a?"<B1-Motion>"
您必须在小部件master.bind(...
上开始运动时使用master
。
此外,您还必须考虑event.x
和event.y
坐标。
import tkinter as tk
class PaintOverWidget(tk.Button):
def __init__(self, master, text):
super().__init__(master, text=text)
self.pack()
master.bind("<B1-Motion>", self.on_motion)
def bbox(self):
# Return a bbox tuple from the `Button` which is `self`
x, y = self.winfo_x(), self.winfo_y()
return x, y, x + self.winfo_width(), y + self.winfo_height()
def on_motion(self, event):
bbox = self.bbox()
if if bbox[0] <= event.x <= bbox[2] and bbox[1] <= event.y <= bbox[3]:
print('on_motion at x:{} y:{}'.format(event.x, event.y))
if __name__ == '__main__':
root = tk.Tk()
root.geometry('200x100')
PaintOverWidget(root, text="UnMark All").mainloop()
输出:
on_motion at x:54 y:15 on_motion at x:55 y:15 on_motion at x:55 y:14 ...
用 Python 测试:3.5 - 'TclVersion':8.6 'TkVersion':8.6
推荐阅读
- reactjs - Next.JS 中不应用嵌套的 CSS 样式
- python - 有没有办法上传图片而无需输入图片的绝对路径
- css - CSS 位置图像
- oracle - 为oracle中的表拍摄快照
- vue.js - Vuetify:通过多个值搜索 v-data-table?
- sql - Postgres SQL查询以获取不同ID的第一行
- c# - 在 ASP.NET Core 3.1 中将 JsonElement 导入 CosmosDB
- flutter - Flutter 上的当前路由名称为空
- php - 在嵌套在页面文件夹中的 php 文档中链接 CSS 文件
- .net-core - 访问发送到自定义记录器 .NETCore 3.1 的参数