Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีผูก Event กับการกดปุ่มเมาส์ซ้ายค้าง (Left Mouse Button Held Down) ใน Tkinter

เพื่อผูก event กับการกดปุ่มเมาส์ซ้ายค้าง ให้ทำตามขั้นตอนด้านล่าง

  • สร้าง instance ของ tkinter frame

  • กำหนดขนาด frame ด้วย win.geometry

  • กำหนด event handler "handler1" พิมพ์ข้อความเมื่อเลื่อนเมาส์ขณะกดปุ่มซ้ายค้าง

  • กำหนด event handler "handler2" พิมพ์ข้อความเมื่อปล่อยปุ่มเมาส์

  • ใช้ bind method ผูก <B1-Motion> กับ handler1

  • ใช้ bind method อีกครั้ง ผูก <ButtonRelease-1> กับ handler2

  • รัน mainloop

ตัวอย่าง

from tkinter import *

win = Tk()
win.geometry("750x250")

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

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

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

win.bind('', handler1)
win.bind('', handler2)

win.mainloop()

ผลลัพธ์

วิธีผูก Event กับการกดปุ่มเมาส์ซ้ายค้าง (Left Mouse Button Held Down) ใน Tkinter

เลื่อนเมาส์ขณะกดปุ่มซ้ายค้าง จะแสดงบนคอนโซล:

You are moving the Mouse with the Left Button Pressed. (หลายบรรทัด)

ปล่อยปุ่มซ้าย จะแสดง:

Button Released