如何将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+ 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告