ใน python tkinter เป็นไลบรารี GUI ที่สามารถใช้สำหรับการเขียนโปรแกรม GUI ต่างๆ แอปพลิเคชันดังกล่าวมีประโยชน์ในการสร้างแอปพลิเคชันเดสก์ท็อป ในบทความนี้ เราจะเห็นแง่มุมหนึ่งของการเขียนโปรแกรม GUI ที่เรียกว่าฟังก์ชันการผูก นี่เป็นการเชื่อมโยงเหตุการณ์เข้ากับฟังก์ชันและเมธอด ดังนั้นเมื่อเหตุการณ์เกิดขึ้น ฟังก์ชันเฉพาะจะถูกดำเนินการ
ผูกเหตุการณ์แป้นพิมพ์
ในตัวอย่างด้านล่าง เราผูกการกดแป้นใดๆ จากแป้นพิมพ์ด้วยฟังก์ชันที่ดำเนินการ เมื่อหน้าต่าง Tkinter GUI เปิดขึ้น เราสามารถกดแป้นใดก็ได้ในแป้นพิมพ์และเราได้รับข้อความว่าแป้นพิมพ์ถูกกด
ตัวอย่าง
from tkinter import *
# Press a buton in keyboard
def PressAnyKey(label):
value = label.char
print(value, ' A button is pressed')
base = Tk()
base.geometry('300x150')
base.bind('<Key>', lambda i : PressAnyKey(i))
mainloop()
ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -

ผูกเหตุการณ์การคลิกเมาส์
ในตัวอย่างด้านล่าง เราจะเห็นวิธีการผูกเหตุการณ์การคลิกเมาส์บนหน้าต่าง tkinter กับการเรียกใช้ฟังก์ชัน ในตัวอย่างด้านล่าง เราเรียกเหตุการณ์เพื่อแสดงการคลิกสองครั้งที่ปุ่มซ้าย คลิกปุ่มขวา และคลิกปุ่มเลื่อนเพื่อแสดงตำแหน่งในแคนวาส tkinter ที่มีการคลิกปุ่ม
ตัวอย่าง
from tkinter import *
from tkinter.ttk import *
# creates tkinter window or root window
base = Tk()
base.geometry('300x150')
# Press the scroll button in the mouse then function will be called
def scroll(label):
print('Scroll button clicked at x = % d, y = % d'%(label.x, label.y))
# Press the right button in the mouse then function will be called
def right_click(label):
print('right button clicked at x = % d, y = % d'%(label.x, label.y))
# Press the left button twice in the mouse then function will be called
def left_click(label):
print('Double clicked left button at x = % d, y = % d'%(label.x, label.y))
Function = Frame(base, height = 100, width = 200)
Function.bind('<Button-2>', scroll)
Function.bind('<Button-3>', right_click)
Function.bind('<Double 1>', left_click)
Function.pack()
mainloop() ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
