如何將Tkinter事件繫結到滑鼠左鍵按下並保持狀態?


要將Tkinter事件繫結到滑鼠左鍵按下並保持狀態,我們可以採取以下步驟:

  • 建立一個Tkinter框架例項。

  • 使用**win.geometry**方法設定框架大小。

  • 定義一個事件處理程式**"handler1"**,當滑鼠左鍵按下並移動時列印一條語句。

  • 定義另一個事件處理程式**"handler2"**,當滑鼠按鈕釋放時列印一條語句。

  • 使用bind方法將**<B1-Motion>**繫結到**handler1**。

  • 再次使用bind方法將**<ButtonRelease-1>**繫結到**handler2**。

  • 最後,執行應用程式視窗的mainloop。

示例

# Import required libraries
from tkinter import *

# Create an instance of tkinter frame
win = Tk()

# Define the geometry of the window
win.geometry("750x250")

# Define a function
def handler1(e):
   print("You are moving the Mouse with the Left Button Pressed.")

def handler2(e):
   print("Button Released")

# Define a Label in Main window
Label(win, text="Move the Mouse with the Left Button Pressed", font='Helvetica 15 underline').pack(pady=30)

# Bind the Mouse events with the Handler
win.bind('<B1-Motion>', handler1)
win.bind('<ButtonRelease-1>', handler2)

win.mainloop()

輸出

執行程式碼後,將顯示以下螢幕:

現在,按下滑鼠左鍵並移動滑鼠,控制檯將顯示以下輸出:

You are moving the Mouse with the Left Button Pressed.

You are moving the Mouse with the Left Button Pressed.

You are moving the Mouse with the Left Button Pressed.

You are moving the Mouse with the Left Button Pressed.

You are moving the Mouse with the Left Button Pressed.

釋放滑鼠左鍵後,將顯示以下內容:

Button Released

更新於:2021年10月26日

3K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告