簡體   English   中英

我怎么能在 hover 上 select window? (Tkinter)

[英]How can I select window on hover? (Tkinter)

是否可以通過將鼠標懸停在 window 上來滾動文本框,即無需單擊 GUI? 我正在使用 tkinter 來開發程序。

所以這是我的解決方案:

from tkinter import Tk, Entry
import pyautogui
from _thread import start_new_thread


def track_motion(root):
    while True:
        while True:
            window_xtl = root.winfo_x()
            window_ytl = root.winfo_y()
            window_xbr = window_xtl + root.winfo_width()
            window_ybr = window_ytl + root.winfo_height()

            mouse_pos = pyautogui.position()
            mouse_x = mouse_pos[0]
            mouse_y = mouse_pos[1]

            if window_xtl < mouse_x < window_xbr and window_ytl < mouse_y < window_ybr:
                for _ in range(500):
                    root.focus_force()

                while True:
                    window_xtl = root.winfo_x()
                    window_ytl = root.winfo_y()
                    window_xbr = window_xtl + root.winfo_width()
                    window_ybr = window_ytl + root.winfo_height()

                    mouse_pos = pyautogui.position()
                    mouse_x = mouse_pos[0]
                    mouse_y = mouse_pos[1]

                    if window_xtl > mouse_x or mouse_x > window_xbr or window_ytl > mouse_y or mouse_y > window_ybr:
                        break


root = Tk()
root.geometry('300x300')
root.attributes('-topmost', True)

start_new_thread(track_motion, (root, ))

entry = Entry(root)
entry.pack()

entry2 = Entry(root)
entry2.pack()

root.mainloop()

為此,您必須使用 pip 安裝pyautoguipip install pyautogui 其工作方式是 window 中的第一個始終位於頂部,這很重要,因為否則突然出現 window 似乎很奇怪。

這里發生的是,首先我們在一個單獨的線程中運行 function,這樣它就不會干擾 tkinter 的.mainloop() In that loop we check the current windows position and current mouse position and then it checks whether the x and y coordinates of the mice are inside the coordinates of the window, and if they are set focus to that window.

我對代碼做了一些更改。 我添加了另一個循環來關閉聚焦,以便可以使用其他小部件。 還注意到 pyautogui 不返回指針尖端的 position,這意味着可以在獲得焦點之前稍微向內移動指針。 還有那個 for 循環,因為出於某種原因需要它,否則它不會獲得焦點。

暫無
暫無

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

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