1.创建
from tkinter import *
root=Tk()
menubar=Menu(root)
def hello():
print('Hello Menu!')
for item in ['Python','Php','CPP']:
menubar.add_command(label=item,command=hello)
root['menu']=menubar
root.mainloop()
图片.png
2.下拉菜单
from tkinter import *
root=Tk()
menubar=Menu(root)
filemenu=Menu(menubar,tearoff=0)
def hello():
print('Hello Menu!')
for item in ['Python','Php','CPP']:
filemenu.add_command(label =item,command=hello)
menubar.add_cascade(label='Language',menu=filemenu)
root['menu']=menubar
root.mainloop()
图片.png
3.添加Checkbutton项
from tkinter import *
root=Tk()
def printItem():
print('Python=',vPython.get())
print('PHP',vPHP.get())
print('CPP=',vCPP.get())
print('C=',vC.get())
print('Java=',vJava.get())
menubar=Menu(root)
vPython=StringVar()
vPHP=StringVar()
vCPP=StringVar()
vC=StringVar()
vJava=StringVar()
filemenu=Menu(menubar,tearoff=0)
for k,v in {'Python':vPython,'PHP':vPHP,'CPP':vCPP,'C':vC,'Java':vJava}.items():
filemenu.add_checkbutton(label=k,command=printItem,variable=v)
menubar.add_cascade(label='Language',menu=filemenu)
root['menu']=menubar
root.mainloop()
root.mainloop()
图片.png
4.添加Radiobutton项
from tkinter import *
root=Tk()
menubar=Menu(root)
vLang=StringVar()
def printItem():
print('vLang=',vLang.get())
filemenu=Menu(menubar,tearoff=0)
for k in ['Python','PHP','CPP','C']:
filemenu.add_radiobutton(label=k,command=printItem,variable=vLang)
menubar.add_cascade(label='Language',menu=filemenu)
root['menu']=menubar
root.mainloop()
图片.png
5.添加分隔符
from tkinter import *
root=Tk()
menubar=Menu(root)
def printItem():
print('add_separator')
filemenu=Menu(menubar,tearoff=0)
for k in ['Python','PHP','CPP','C']:
filemenu.add_command(label=k,command=printItem)
filemenu.add_separator()
menubar.add_cascade(label='Language',menu=filemenu)
root['menu']=menubar
root.mainloop()
图片.png
6.快捷菜单
from tkinter import *
root=Tk()
menubar=Menu(root)
def printItem():
print('popup menu')
filemenu=Menu(menubar,tearoff=0)
for k in ['Python','PHP','CPP','C']:
filemenu.add_command(label=k,command=printItem)
filemenu.add_separator()
menubar.add_cascade(label='Language',menu=filemenu)
def popup(event):
menubar.post(event.x_root,event.y_root)
root.bind('<Button-3>',popup)
root.mainloop()
图片.png
7.菜单项的操作
from tkinter import *
root=Tk()
menubar=Menu(root)
def printItem():
print('add_separator')
filemenu=Menu(menubar,tearoff=0)
for k in range(5):
filemenu.add_command(label=str(k),command=printItem)
menubar.add_cascade(label='Language',menu=filemenu)
filemenu.insert_command(1,label='1000',command=printItem)
filemenu.insert_checkbutton(2,label='2000',command=printItem)
filemenu.insert_radiobutton(3,label='3000',command=printItem)
filemenu.insert_separator(1)
filemenu.insert_separator(5)
filemenu.delete(6,9)
filemenu.delete(0)
root['menu']=menubar
root.mainloop()
图片.png
网友评论