사용자 상호 작용이 필요한 응용 프로그램에는 메뉴 모음이 필요합니다. 메뉴(상위)를 초기화하여 메뉴를 생성할 수 있습니다. 메뉴 항목과 함께 개체. 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() 출력
위의 코드를 실행하면 레이블과 버튼이 있는 창이 표시됩니다. 마우스 오른쪽 버튼을 클릭하면 팝업 메뉴가 창에 나타납니다.
