簡體   English   中英

如何通過“繪畫”來觸發按鈕? 使用 tkinter 的“B1-Motion”?

[英]How can I trigger a Button by 'painting' over it? using tkinter's "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 的"<B1-Motion>"事件通過在其上“繪畫”來觸發Button

您必須使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM