是否有可能在2秒不活动后鼠标左键点击- Tkinter



我正在用Tkinter, python制作一个GUI,可以使用鼠标光标导航,但没有按钮/键。

我正试图解决当前的问题,有鼠标左键点击没有任何人按物理鼠标按钮或键盘上的一个键。我想有鼠标自动点击后2秒不活动。

例如,我将鼠标悬停在按钮上,等待两秒钟,然后按钮被按下。

我想说我已经尝试了所有的东西,但我找不到任何尝试。我想使用。invoke()函数与定时循环,但我不能让它运行,而我的gui是打开的。我会展示我的GUI代码。也许我做错了什么,但如果我把。invoke函数后的胜利。主循环,它甚至不会运行,直到我关闭GUI tk窗口。

win = Tk()
# get the dimensions of the primary screen
app = wx.App(False)
w, h = wx.GetDisplaySize()
geometry = "%dx%d" % (w,h)
win.geometry(geometry)
win.attributes('-fullscreen', True)
win.config(cursor="circle")
# get the grid image
bg = Image.open('grid_image.png')
img = bg.resize((w, h))
grid_img=ImageTk.PhotoImage(img)
image_label = Label(win, image=grid_img)
image_label.place(x=0, y=0, relwidth=1, relheight=1)
# print an image of a green circle
gw = int(w/26)
gh = int(h/15)
g_circle = Image.open('green_circle.png')
g_img = g_circle.resize((gw,gh))
g_circle_image=ImageTk.PhotoImage(g_img)
g_label = Label(win, image=g_circle_image)
g_label.place(x=w/8, y=h/8)
g_btn = Button(win, image=g_circle_image, command=win.destroy)
g_btn.place(x=(w/8), y=(h/8))
# print an image of a blue circle
bw = int(w/26)
bh = int(h/15)
b_circle = Image.open('circle.png')
b_img = b_circle.resize((bw,bh))
b_circle_image=ImageTk.PhotoImage(b_img)
b_label = Label(win, image=b_circle_image)
b_label.place(x=(w/8)*5, y=(h/8)*5)
b_btn = Button(win, image=b_circle_image, command=win.destroy)
b_btn.place(x=(w/8)*5, y=(h/8)*5)
win.mainloop()

如果你能帮我解决这个问题,我将不胜感激。

由于您似乎已经确认了tk.Button().invoke()的选项,您可以使用tk.Button.bind('<Enter>', _onhover)来检测按钮上的鼠标和tk.Button.bind('<Leave>', _onleave)

定义如下两个函数:

def _onhover(event):
global _current_button
button = event.widget
_current_button = button
button.after(2000, lambda b=button: _invocation(b))
def _onleave(event):
global _current_button
_current_button = None
def _invocation(button):
if _current_button is button:
button.invoke()

最新更新