简体   繁体   English

Python/Tkinter 的鼠标绑定问题

[英]Mouse Binding Question with Python/Tkinter

Wondering how to bind an event to the left mouse button but not having to be hovered in the window/app/root.想知道如何将事件绑定到鼠标左键,但不必将鼠标悬停在窗口/应用程序/根目录中。 Basically, I want the event to happen where-ever my mouse pointer happens to be on my screen.基本上,我希望事件发生在我的鼠标指针碰巧在我的屏幕上的任何地方。 Right now I can only figure out how to make the mouse button bindings work when the mouse is hovered on the window/app/root.现在我只能弄清楚当鼠标悬停在窗口/应用程序/根目录上时如何使鼠标按钮绑定起作用。

    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()

You cannot do this with tkinter, you'll have to find some platform-specific way to do it.你不能用 tkinter 做到这一点,你必须找到一些特定于平台的方法来做到这一点。 Tkinter can only process events when it is the application in focus. Tkinter 只能在应用程序处于焦点时处理事件。

This is not something that can be done with Tkinter, but rather ' Pyautogui '这不是 Tkinter 可以做到的,而是“ Pyautogui

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM