首页 > 解决方案 > 如何通过“绘画”来触发按钮?使用 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()

运行时,它成功报告单击,但如果我单击窗口中的其他位置并拖动按钮,它无法报告它已被“绘制”。

出了什么问题,我该如何解决?

标签: pythontkinter

解决方案


问题:使用 tkinter 的事件Button通过“绘画”触发 a?"<B1-Motion>"

您必须在小部件master.bind(...上开始运动时使用master
此外,您还必须考虑event.xevent.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


推荐阅读