【问题标题】:Mouse Binding Question with Python/TkinterPython/Tkinter 的鼠标绑定问题
【发布时间】:2022-01-13 18:42:44
【问题描述】:

想知道如何将事件绑定到鼠标左键,但不必将鼠标悬停在窗口/应用程序/根目录中。基本上,我希望事件发生在我的鼠标指针碰巧在我的屏幕上的任何地方。现在我只能弄清楚当鼠标悬停在窗口/应用程序/根上时如何使鼠标按钮绑定起作用。

    from tkinter import*
    from tkinter import Tk, Label, StringVar
    import random
    import pyautogui

    root = Tk()
    root.configure(background='black')
    root.attributes("-topmost", True)
    root.overrideredirect(True)
    root.geometry("100x100")

    title_bar = Frame(root, bg='black')
    title_bar.pack(side=TOP, fill=X)

    tout = StringVar()
    label = Label(root, textvariable=tout, font=('TkDefaultFont', 
    50), bg='black', fg='red')
    label.pack()

    def _quit():
        root.quit()
        root.destroy()

    def move_app(event):
        root.geometry(f'+{event.x_root}+{event.y_root}')

    def gen_rand(event):
        randvar = random.randint(0,99)
        tout.set(randvar)

    def clear_rand(event):
        tout.set("")

    myButton = Button(title_bar, text="X", font=('TkDefaultFont', 5), 
    bg='black', activebackground='red', fg='red', command=_quit)
    myButton.pack(side=RIGHT)

    root.bind('<Button-1>', gen_rand)
    root.bind('<Button-3>', clear_rand)
    root.bind("<B2-Motion>", move_app)

    root.mainloop()

【问题讨论】:

    标签: python tkinter binding window mouse


    【解决方案1】:

    你不能用 tkinter 做到这一点,你必须找到一些特定于平台的方法来做到这一点。 Tkinter 只能在应用程序处于焦点时处理事件。

    【讨论】:

      【解决方案2】:

      这不是 Tkinter 可以做到的, 而是 Pyautogui 来生成事件

      pyautogui.click(x=100, y=200)  # move to 100, 200, then click the left mouse button.
      

      如果你想读取一个事件,你必须使用其他模块,例如 pynput How to know if the left mouse click is pressed

      from pynput import mouse
      
      def on_click(x, y, button, pressed):
          if button == mouse.Button.left:
              print('{} at {}'.format('Pressed Left Click' if pressed else 'Released Left Click', (x, y)))
              return False # Returning False if you need to stop the program when Left clicked.
          else:
              print('{} at {}'.format('Pressed Right Click' if pressed else 'Released Right Click', (x, y)))
      
      listener = mouse.Listener(on_click=on_click)
      listener.start()
      listener.join()```
      
        [1]: https://pypi.org/project/PyAutoGUI/
        [2]: https://stackoverflow.com/questions/39235454/how-to-know-if-the-left-mouse-click-is-pressed
      

      【讨论】:

      • 感谢您的回复。我似乎仍然被卡住了。我安装了 pyautogui 并导入了它,但不确定代码的外观。我刚刚在原始问题中发布了代码
      • 哦,我的错,pyautogui 只能在你想监听事件时才能创建一个事件,你必须使用其他模块,例如 pynput。我将编辑我的答案
      • 感谢您的所有帮助。我对这个很陌生,我还是迷路了。我只想让我的随机数生成器通过左键更改数字,无论光标在哪里。
      猜你喜欢
      • 2023-02-13
      • 1970-01-01
      • 1970-01-01
      • 2016-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多