在 Tkinter 中繫結滑鼠雙擊


假設針對某個特定應用程式,我們要繫結滑鼠雙擊,以便其執行某個事件或操作。我們可以使用 bind(‘<Double-Button-1>’, handler) bind(‘<Double-Button-2>’, handler) 方法將滑鼠左右按鈕與處理程式或回撥函式繫結在一起。

示例

在本示例中,我們將建立一個包含按鈕的應用程式。當我們雙擊按鈕時,它將開啟一個彈出視窗。

#Import required libraries
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter frame
win= Tk()
#Define the geometry of the window
win.geometry("750x250")
#Define a function
def handler(e):
   top= Toplevel(win)
   top.geometry("600x200")
   Label(top, text= "Hey There!", font= ('Helvetica 15 bold')).pack(pady=30)

#Define a Label in Main window
Label(win, text= "Double Click to Open the Popup",font=('Helvetica 15 underline')).pack(pady=30)

#Create a Button
ttk.Button(win, text= "Click", command=lambda:handler).pack(pady=20)

#Bind the Double Click with the Handler
win.bind('<Double-Button-1>', handler)
win.mainloop()

輸出

現在,執行以上程式碼以顯示視窗。

雙擊按鈕“點選”以開啟一個彈出視窗。

更新於:2021 年 5 月 3 日

3K+ 瀏覽量

開啟你的 職業

完成此課程以取得認證

開始吧
廣告