tkinter菜单中文说明页

Menu类可以用来创建顶级菜单、弹出菜单、下拉菜单(pop-up, toplevel and pull-down)。

有一种叫做可选菜单的小部件可以用OptionMenu类来生成。它可以让你从一个列表中选择一个项目。

语法

下面是创建菜单的简单语法形式:

w = Menu ( master, option, ... )

参数

  • master ? 这是父窗口.

  • options ? 这是可选项,由下面的键值对提供。

Sr.No. Description
1

activebackground

鼠标指针悬停在菜单项目上时的背景色。

2

activeborderwidth

鼠标指针悬停时菜单项目的宽度,默认为1个像素宽。

3

activeforeground

鼠标指针悬停时菜单项目的前景颜色。

4

bg

鼠标指针非悬停时菜单项目们的背景色。

5

bd

菜单项目们的边宽的宽度值,默认为1个像素。

6

cursor

指定鼠标指针光标, but only when the menu has been torn off.

7

disabledforeground

状态为禁用的菜单项目的文本颜色

8

font

所选文本的默认字体

9

fg

指定前景色

10

postcommand

你可以将此选项设置为一个函数,每次有人打开此菜单时都会调用该函数。

11

relief

默认的3D效果菜单的这个参数值为RAISED.

12

image

在菜单按钮上显示一幅图像。

13

selectcolor

单选钮或复选框被选中时的颜色。

14

tearoff

通常菜单可以独立。如果设置tearoff=0, 菜单就不能单独在其它地方显示了。

15

title

独立出去后菜单最上面的标题。

方法

下面是Menu可用的方法 ?

Sr.No. Option & Description
1

add_command (options)

给菜单增加一个项目

2

add_radiobutton( options )

给菜单创建一个单选按扭

3

add_checkbutton( options )

给菜单创建一个复选按扭

4

add_cascade(options)

创建次级菜单

5

add_separator()

增加分隔符

6

add( type, options )

增加特定类型的项目

7

delete( startindex [, endindex ])

根据起始索引号和结束索引号删除菜单项目

8

entryconfig( index, options )

根据菜单项目的索引号配置菜单项目

9

index(item)

根据菜单条目的标签返回索引号

10

insert_separator ( index )

在指定索引号的位置插入分隔符

11

invoke ( index )

直接调用菜单项目所对应的函数。如果是复选框则会触发set和clear函数。如果是单选钮则调用set

12

type ( index )

根据索引号返回菜单项目的类型。 either “cascade”, “checkbutton”, “command”, “radiobutton”, “separator”, or “tearoff”.

举例

你是最棒的,请自行输入以下代码测试!

from tkinter import *

def donothing():
   filewin = Toplevel(root)
   button = Button(filewin, text="Do nothing button")
   button.pack()
   
root = Tk()
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=1)
filemenu.add_command(label="New", command=donothing)
filemenu.add_command(label="Open", command=donothing)
filemenu.add_command(label="Save", command=donothing)
filemenu.add_command(label="Save as...", command=donothing)
filemenu.add_command(label="Close", command=donothing)

filemenu.add_separator()

filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
editmenu = Menu(menubar, tearoff=0)
editmenu.add_command(label="Undo", command=donothing)

editmenu.add_separator()

editmenu.add_command(label="Cut", command=donothing)
editmenu.add_command(label="Copy", command=donothing)
editmenu.add_command(label="Paste", command=donothing)
editmenu.add_command(label="Delete", command=donothing)
editmenu.add_command(label="Select All", command=donothing)

menubar.add_cascade(label="Edit", menu=editmenu)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Help Index", command=donothing)
helpmenu.add_command(label="About...", command=donothing)
menubar.add_cascade(label="Help", menu=helpmenu)

root.config(menu=menubar)
root.mainloop()

        

本页由李兴球翻译,原网址:https://www.tutorialspoint.com/python/tk_menu.htm

关于李兴球

李兴球的博客是Python创意编程原创博客
此条目发表在python, tkinter分类目录。将固定链接加入收藏夹。