首先安装tkinter库,并引入:
import tkinter as tk
创建父菜单,然后把子菜单放进去:
# 新建一个顶级menu
menuTop = tk.Menu(root)
menuSun = tk.Menu(menuTop, tearoff=0)
menu1 = menuSun.add_command(label='新建', command=lambda: xz(menuSun, 0))
menu2 = menuSun.add_command(label='编辑', command=lambda: xz(menuSun, 1))
menu3 = menuSun.add_command(label='删除', command=lambda: xz(menuSun, 2))
# 把子菜单加到顶级菜单中
menuTop.add_cascade(label='txt', menu=menuSun)
把整个菜单放到窗口中:
root.config(menu=menuTop)
打印对应选中的子菜单label属性方法:
def xz(text, i):
x = text.entrycget(i, "label")
print(x)
输出结果:
完整代码:
import tkinter as tk
root = tk.Tk()
root.title('tkinter下拉菜单')
# 输出对应子菜单的label值
def xz(text, i):
x = text.entrycget(i, "label")
print(x)
# 新建一个顶级menu
menuTop = tk.Menu(root)
menuSun = tk.Menu(menuTop, tearoff=0)
menu1 = menuSun.add_command(label='新建', command=lambda: xz(menuSun, 0))
menu2 = menuSun.add_command(label='编辑', command=lambda: xz(menuSun, 1))
menu3 = menuSun.add_command(label='删除', command=lambda: xz(menuSun, 2))
# 把子菜单加到顶级菜单中
menuTop.add_cascade(label='txt', menu=menuSun)
root.config(menu=menuTop)
root.mainloop()