簡體   English   中英

Tkinter:僅在按下鼠標按鈕時獲取鼠標坐標

[英]Tkinter: Get mouse coordinates only when mouse button is pressed

我在 Python 中有一個相當具體的問題。

我知道在 Tkinter 的框架上不斷接收鼠標坐標的解決方案:

import Tkinter as tk
root = tk.Tk()

def motion(event):
    x, y = event.x, event.y
    print('{}, {}'.format(x, y))

root.bind('<Motion>', motion)
root.mainloop()

我的問題現在結合按下按鈕和動作事件。 簡而言之:我只在按下按鈕時才想要鼠標坐標,而不是在釋放或未按下時。

def ButtonPress(event):
    #This is the part, where I can't figure out, how to proceed.
    #How can I call the motion event from here.


Bt = Button(root, text='Press for coordinates!')
Bt.bind('<ButtonPress>', ButtonPress)

問候!

至少有兩個非常簡單的解決方案:

  • 在按鈕按下/釋放時設置/取消設置標志,如果設置了標志,則在您的函數中僅打印坐標,
  • 綁定/取消綁定按鈕按下/釋放時的運動事件。

設置標志

此示例使用一個名為旗do_capture被設置為True按下一個按鈕,並設置為False上的按鈕釋放:

import Tkinter as tk
root = tk.Tk()

def motion(event):
    if do_capture:
        x, y = event.x, event.y
        print('{}, {}'.format(x, y))

def capture(flag):
    global do_capture
    do_capture = flag

root.bind('<Motion>', motion)
root.bind("<ButtonPress-1>", lambda event: capture(True))
root.bind("<ButtonRelease-1>", lambda event: capture(False))

capture(False)

root.mainloop()

綁定/解綁

在這個例子中,我們在按下按鈕時綁定<Motion>事件並在釋放時解除綁定:

import Tkinter as tk
root = tk.Tk()

def motion(event):
    x, y = event.x, event.y
    print('{}, {}'.format(x, y))

def capture(flag):
    if flag:
        root.bind('<Motion>', motion)
    else:
        root.unbind('<Motion>')

root.bind("<ButtonPress-1>", lambda event: capture(True))
root.bind("<ButtonRelease-1>", lambda event: capture(False))

root.mainloop()

如果您不想在動作回調中存儲鼠標位置,然后在按鈕的回調中再次讀取它,您可以使用winfo_pointer()獲取屏幕上的絕對指針位置並減去窗口位置winfo_root()得到相對於窗口的指針位置。

當然,您需要自己捕捉窗口外的指針位置。

暫無
暫無

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

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