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

วิธี Bind ปุ่ม Enter ให้กับฟังก์ชันใน Tkinter


ภาพรวม

การกดปุ่มและจัดการ Event ด้วยปุ่มนั้น ใช้ Binding Method ในแอป Tkinter เมื่อกดปุ่ม จะเรียก Handler ที่ทำ Operation สำหรับ Key Event

ถ้าต้องการ Bind Enter Key กับ bind function ใช้ bind('', Handler) สำหรับ Enter Key ใช้ bind('', Handler)

ตัวอย่างโค้ด

# Import the tkinter library
from tkinter import *
# Create an instance of tkinter frame
win = Tk()
# Set the geometry
win.geometry("650x250")
def handler(e):
    label = Label(win, text="You Pressed Enter")
    label.pack()
# Create a Label
Label(win, text="Press Enter on the Keyboard", font=('Helvetica bold', 14)).pack(pady=20)
# Bind the Enter Key to Call an event
win.bind('', handler)
win.mainloop()

ผลลัพธ์

จะแสดงหน้าต่างดังนี้

วิธี Bind ปุ่ม Enter ให้กับฟังก์ชันใน Tkinter

กด "Enter" บนแป้นพิมพ์ จะแสดง "You Pressed Enter"

วิธี Bind ปุ่ม Enter ให้กับฟังก์ชันใน Tkinter