เราต้องการแถบเมนูในแอปพลิเคชันที่จำเป็นต้องมีการโต้ตอบกับผู้ใช้ สามารถสร้างเมนูได้โดยการเริ่มต้น เมนู (หลัก) วัตถุพร้อมกับรายการเมนู สามารถสร้างเมนูป๊อปอัปได้โดยการเริ่มต้น tk_popup(x_root,y_root, False) ซึ่งทำให้มั่นใจได้ว่าเมนูจะปรากฏบนหน้าจอ ตอนนี้ เราจะเพิ่มเหตุการณ์ที่สามารถเรียกใช้ผ่านปุ่มเมาส์ (คลิกขวา) grab_release() วิธีตั้งค่าให้ปล่อยปุ่มเมาส์เพื่อยกเลิกการตั้งค่าเมนูป๊อปอัป
ตัวอย่าง
#Import the required libraries
from tkinter import *
from tkinter import ttk
#Create an instance of Tkinter frame
win = Tk()
#Set the geometry of the Tkinter library
win.geometry("700x350")
label = Label(win, text="Right-click anywhere to display a menu", font= ('Helvetica 18'))
label.pack(pady= 40)
#Add Menu
popup = Menu(win, tearoff=0)
#Adding Menu Items
popup.add_command(label="New")
popup.add_command(label="Edit")
popup.add_separator()
popup.add_command(label="Save")
def menu_popup(event):
# display the popup menu
try:
popup.tk_popup(event.x_root, event.y_root, 0)
finally:
#Release the grab
popup.grab_release()
win.bind("<Button-3>", menu_popup)
button = ttk.Button(win, text="Quit", command=win.destroy)
button.pack()
mainloop() ผลลัพธ์
การเรียกใช้โค้ดด้านบนจะแสดงหน้าต่างที่มีป้ายกำกับและปุ่ม เมื่อเราคลิกขวาด้วยเมาส์ เมนูป๊อปอัปจะปรากฏขึ้นในหน้าต่าง
