Tkinter 菜单和工具栏

文章更新于:2020-04-26
注0:原英文教程地址:zetcode.com
注1:Introduction to Tkinter 参见:关于Tkinter的介绍
注2:Layout management in Tkinter 参见:Tkinter布局管理器
注3:Tkinter widgets 参见:Tkinter 控件

Menus & toolbars in Tkinter

In this part of the Tkinter tutorial, we will work with menus and toolbar.

本章,我们学习菜单和工具栏

A menubar is one of the most visible parts of the GUI application. It is a group of commands located in various menus.

While in console applications we must remember many arcane commands, here we have most of the commands grouped into logical parts.

There are accepted standards that further reduce the amount of time spending to learn a new application. Menus group commands that we can use in an application.

Toolbars provide a quick access to the most frequently used commands.

菜单栏是图形化程序最显眼的部分之一。
它是在菜单中的一组命令。
在控制台程序中,我们需要记住很多晦涩的命令。
但在这,我们很多命令都集成在了菜单中。

有公认的标准可以进一步减少学习新应用程序的时间。
菜单可以将我们平时使用的命令分组。
工具栏提供一些我们最常使用的命令。

Tkinter simple menu

The first example shows a simple menu.

第一个例子是展示一个简单的菜单。

#!/usr/bin/env python3

"""
ZetCode Tkinter tutorial

This program shows a simple
menu. It has one action, which
will terminate the program, when
selected.

Author: Jan Bodnar
Last modified: April 2019
Website: www.zetcode.com
"""

from tkinter import Tk, Frame, Menu

class Example(Frame):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        self.master.title("Simple menu")

        menubar = Menu(self.master)
        self.master.config(menu=menubar)

        fileMenu = Menu(menubar)
        fileMenu.add_command(label="Exit", command=self.onExit)
        menubar.add_cascade(label="File", menu=fileMenu)


    def onExit(self):

        self.quit()


def main():

    root = Tk()
    root.geometry("250x150+300+300")
    app = Example()
    root.mainloop()


if __name__ == '__main__':
    main()

Our example will show a menu with one item. By selecting the exit menu item we close the application.
我们这里例子将展示一个只有一个选项的菜单。
通过选择这个 exit 选项来关闭这个应用程序。

menubar = Menu(self.master)
self.master.config(menu=menubar)

Here we create a menubar. It is a regular Menu widget configured to be the menubar of the root window.

这里我们创建了一个菜单栏。
这是一个常规的菜单控件,它放置在窗口的根窗口。

fileMenu = Menu(menubar)

We create a file menu object. A menu is a drop-down window containing commands.

我们创建了一个菜单对象。
菜单对象是一个包含命令的下拉窗口。

fileMenu.add_command(label="Exit", command=self.onExit)

We add a command to the file menu. The command will call the onExit() method.
我们在 file 菜单上添加了一个命令。
这个命令调用 onExit() 方法。

menubar.add_cascade(label="File", menu=fileMenu)

The file menu is added to the menubar using the add_cascade() method.

这个 file 菜单通过调用 add_cascade() 方法添加到菜单栏。

在这里插入图片描述

Tkinter submenu

A submenu is a menu plugged into another menu object. The next example demonstrates this.

一个子菜单是插入在另一个菜单中的对象。
下一个例子中我们进行演示。

#!/usr/bin/env python3

"""
ZetCode Tkinter tutorial

In this script we create a submenu
a separator and keyboard shortcuts to menus.

Author: Jan Bodnar
Last modified: April 2019
Website: www.zetcode.com
"""

from tkinter import Tk, Frame, Menu

class Example(Frame):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        self.master.title("Submenu")

        menubar = Menu(self.master)
        self.master.config(menu=menubar)

        fileMenu = Menu(menubar)

        submenu = Menu(fileMenu)
        submenu.add_command(label="New feed")
        submenu.add_command(label="Bookmarks")
        submenu.add_command(label="Mail")
        fileMenu.add_cascade(label='Import', menu=submenu, underline=0)

        fileMenu.add_separator()

        fileMenu.add_command(label="Exit", underline=0, command=self.onExit)
        menubar.add_cascade(label="File", underline=0, menu=fileMenu)


    def onExit(self):

        self.quit()


def main():

    root = Tk()
    root.geometry("250x150+300+300")
    app = Example()
    root.mainloop()


if __name__ == '__main__':
    main()

In the example, we have three options in a submenu of a file menu. We create a separator and keyboard shortcuts.

在这里例子中,我们在 file 菜单的子菜单中设置了三个选项。
我们创建一个分隔符和键盘快捷键。

submenu = Menu(fileMenu)
submenu.add_command(label="New feed")
submenu.add_command(label="Bookmarks")
submenu.add_command(label="Mail")

We have a submenu with three commands. The submenu is a regular menu.

我们设置了一个有三个命令的子菜单。
这个子菜单是一个常规菜单。

fileMenu.add_cascade(label='Import', menu=submenu, underline=0)

By adding the menu to the fileMenu and not to the menubar, we create a submenu.
The underline parameter creates a keyboard shortcut. It provides the character position which should be underlined.

In our case it is the first. Positions start from zero. When we click on the File menu, a popup window is shown.
The Import menu has one character underlined. We can select it either with the mouse pointer or with the Alt+I shortcut.

我们在文件菜单上添加一个子菜单而不是直接在菜单栏上添加。
underline 参数创建了一个键盘快捷键。
它提供了一个应该加下划线的字符位置,在我们这里例子,是在第一个。
位置从零开始。

当我们点击文件菜单,一个弹出式窗口将会显示。
导入菜单有一个下划线符号。
我们可以使用鼠标指针或者 Alt + T 快捷键来选择它。

fileMenu.add_separator()

A separator is a horizontal line that visually separates menu commands. This way we can group items into some logical places.

一个 separator 是一个分隔命令的水平线,用于将命令划分成逻辑组。
在这里插入图片描述

Tkinter Popup menu

In the next example, we create a popup menu. Popup menu is also called a context menu. It can be shown anywhere on the client area of a window.

在下一个例子,我们将创建一个弹出式菜单。
弹出式菜单也叫上下文菜单
它可以在窗口客户端区的任意位置显示。

#!/usr/bin/env python3

"""
ZetCode Tkinter tutorial

In this program, we create
a popup menu.

Author: Jan Bodnar
Last modified: April 2019
Website: www.zetcode.com
"""

from tkinter import Tk, Frame, Menu

class Example(Frame):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        self.master.title("Popup menu")
        self.menu = Menu(self.master, tearoff=0)
        self.menu.add_command(label="Beep", command=self.bell)
        self.menu.add_command(label="Exit", command=self.onExit)

        self.master.bind("<Button-3>", self.showMenu)
        self.pack()


    def showMenu(self, e):

        self.menu.post(e.x_root, e.y_root)


    def onExit(self):

        self.quit()


def main():

    root = Tk()
    root.geometry("250x150+300+300")
    app = Example()
    root.mainloop()


if __name__ == '__main__':
    main()

In our example, we create a popup menu with two commands.

在这个例子中,我们创建一个有两个命令的弹出式菜单。

self.menu = Menu(self.master, tearoff=0)

A context menu is a regular Menu widget. The tearoff feature is turned off. Now it is not possible to separate the menu into a new toplevel window.

一个上下文菜单也是常规组件。
tearoff 特性已经关掉,
所以它不可以独立出来成为一个悬浮窗口了。

self.master.bind("<Button-3>", self.showMenu)

We bind the event to the showMenu() method. The event is generated when we right click on the client area of the window.

我们将 <Button-3> 事件绑定上 showMenu() 方法。
这个事件当我们在窗口客户端区右键的时候将被触发。

def showMenu(self, e):
self.menu.post(e.x_root, e.y_root)

The showMenu() method shows the context menu. The popup menu is shown at the x and y coordinates of the mouse click.

这个 showMenu() 方法显示上下文菜单。
这个菜单从右键的位置开始显示。

在这里插入图片描述

Tkinter toolbar

Menus group commands that we can use in an application. Toolbars provide a quick access to the most frequently used commands. There is no toolbar widget in Tkinter.

我们可以在程序中使用菜单组命令。
而工具栏则提供了更便捷的方法来使用我们频繁使用到的命令。
不过 Tkinter 中没有提供工具栏控件。

#!/usr/bin/env python3

"""
ZetCode Tkinter tutorial

In this program, we create a toolbar.

Author: Jan Bodnar
Last modified: April 2019
Website: www.zetcode.com
"""

from PIL import Image, ImageTk
from tkinter import Tk, Frame, Menu, Button
from tkinter import LEFT, TOP, X, FLAT, RAISED


class Example(Frame):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        self.master.title("Toolbar")

        menubar = Menu(self.master)
        self.fileMenu = Menu(self.master, tearoff=0)
        self.fileMenu.add_command(label="Exit", command=self.onExit)
        menubar.add_cascade(label="File", menu=self.fileMenu)

        toolbar = Frame(self.master, bd=1, relief=RAISED)

        self.img = Image.open("exit.png")
        eimg = ImageTk.PhotoImage(self.img)

        exitButton = Button(toolbar, image=eimg, relief=FLAT,
            command=self.quit)
        exitButton.image = eimg
        exitButton.pack(side=LEFT, padx=2, pady=2)

        toolbar.pack(side=TOP, fill=X)
        self.master.config(menu=menubar)
        self.pack()


    def onExit(self):
        self.quit()


def main():

    root = Tk()
    root.geometry("250x150+300+300")
    app = Example()
    root.mainloop()


if __name__ == '__main__':
    main()

Our toolbar is on a frame on which we put a button.

我们在一个框架上放上一个按钮来当做工具栏。

toolbar = Frame(self.master, bd=1, relief=RAISED)

A toolbar is created. It is a Frame. We created a raised border so that the boundaries of a toolbar are visible.

这里我们创建了一个框架。
我们创建了一个凸起的边框线以示工具栏的边界。

self.img = Image.open("exit.png")
eimg = ImageTk.PhotoImage(self.img)

Image and a photo image for the toolbar button are created.

创建工具栏按钮需要的图片。

exitButton = Button(toolbar, image=eimg, relief=FLAT,
    command=self.quit)

Button widget is created.

创建按钮。

exitButton.pack(side=LEFT, padx=2, pady=2)

The toolbar is a frame and a frame is a container widget. We pack the button to the left side and add some padding.

工具栏是一个框架,一个作为小控件容器的框架。
我们在左边放置了一个按钮和一些内边距。

toolbar.pack(side=TOP, fill=X)

The toolbar itself is packed to the top of the toplevel window; it is horizontally stretched.

工具栏被放在根窗口的顶部。
他是水平扩展的。
在这里插入图片描述

In this part of the Tkinter tutorial, we worked with menus and toolbars.

在本章节,我们学习了菜单和工具栏。

  • 0
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Python Tkinter提供了创建菜单工具栏的功能,可以实现多窗口的应用程序。可以使用Menu类创建菜单,使用Toolbar类创建工具栏,使用Toplevel类创建多个窗口。 下面是一个使用Tkinter创建菜单工具栏的示例代码: ```python from tkinter import Tk, Frame, Menu, Button, Toplevel class Example(Frame): def __init__(self): super().__init__() self.initUI() def initUI(self): self.master.title("Menu and Toolbar") menubar = Menu(self.master) self.master.config(menu=menubar) fileMenu = Menu(menubar) fileMenu.add_command(label="New Window", command=self.createNewWindow) fileMenu.add_command(label="Exit", command=self.onExit) menubar.add_cascade(label="File", menu=fileMenu) toolbar = Frame(self.master, bd=1, relief="raised") toolbar.pack(side="top", fill="x") newButton = Button(toolbar, text="New", command=self.createNewWindow) newButton.pack(side="left") exitButton = Button(toolbar, text="Exit", command=self.onExit) exitButton.pack(side="left") def createNewWindow(self): top = Toplevel(self.master) top.title("New Window") def onExit(self): self.quit() def main(): root = Tk() app = Example() root.mainloop() if __name__ == '__main__': main() ``` 在上面的示例代码中,我们首先创建一个`Example`类,继承自`Frame`类。在`initUI`方法中,我们创建了一个菜单栏和一个工具栏菜单栏中有一个"File"菜单,包含"New Window"和"Exit"选项。工具栏中有一个"New"按钮和一个"Exit"按钮。当用户点击"New Window"选项或"New"按钮时,会创建一个新的顶级窗口。当用户点击"Exit"选项或"Exit"按钮时,会退出程序
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值