如何在 Tkinter 中建立彈出式選單?


在需要使用者互動的應用程式中需要選單欄。可以透過對選單項一起初始化 Menu(parent) 物件來建立選單。可以透過初始化 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()

輸出

執行以上程式碼將顯示一個帶有標籤和按鈕的視窗。當我們用滑鼠右鍵單擊時,視窗中會出現一個彈出選單。

更新於: 25-5-2021

4k+ 瀏覽量

開啟您的職業生涯

完成課程,獲得認證

開始
廣告