PyGobject(五十九)布局容器之Menu

在介绍Gtk.Menu之前,必须要先了解Gtk.MenuShell这个抽象类,Gtk.Menu和Gtk.MenuBar实现了Gtk.MenuShell抽象类的接口

Gtk.MenuShell

继承关系

Gtk.MenuShell是Gtk.Container的直接子类,Gtk.MenuShell是一个抽象类
这里写图片描述

Methods

方法修饰词方法名及参数
activate_item (menu_item, force_deactivate)
append (child)
bind_model (model, action_namespace, with_separators)
cancel ()
deactivate ()
deselect ()
get_parent_shell ()
get_selected_item ()
get_take_focus ()
insert (child, position)
prepend (child)
select_first (search_sensitive)
select_item (menu_item)
set_take_focus (take_focus)

Virtual Methods

do_activate_current (force_hide)
do_cancel ()
do_deactivate ()
do_get_popup_delay ()
do_insert (child, position)
do_move_current (direction)
do_move_selected (distance)
do_select_item (menu_item)
do_selection_done ()

Properties

NameTypeFlagsShort Description
take-focusboolr/w/enA boolean that determines whether the menu grabs the keyboard focus

Signals

NameShort Description
activate-currentAn action signal that activates the current menu item within the menu shell.
cancelAn action signal which cancels the selection within the menu shell.
cycle-focusA keybinding signal which moves the focus in the given direction.
deactivateThis signal is emitted when a menu shell is deactivated.
insertThe ::insert signal is emitted when a new Gtk.MenuItem is added to a Gtk.MenuShell.
move-currentAn keybinding signal which moves the current menu item in the direction specified by direction.
move-selectedThe ::move-selected signal is emitted to move the selection to another item.
selection-doneThis signal is emitted when a selection has been completed within a menu shell.

Gtk.MenuBar

继承关系

这里写图片描述

Methods

方法修饰词方法名及参数
staticnew ()
staticnew_from_model (model)
get_child_pack_direction ()
get_pack_direction ()
set_child_pack_direction (child_pack_dir)
set_pack_direction (pack_dir)

Properties

NameTypeFlagsShort Description
child-pack-directionGtk.PackDirectionr/w/enThe child pack direction of the menubar
pack-directionGtk.PackDirectionr/w/enThe pack direction of the menubar

Gtk.Menu

继承关系

这里写图片描述

Methods

方法修饰词方法名及参数
staticget_for_attach_widget (widget)
staticnew ()
staticnew_from_model (model)
attach (child, left_attach, right_attach, top_attach, bottom_attach)
attach_to_widget (attach_widget, detacher)
detach ()
get_accel_group ()
get_accel_path ()
get_active ()
get_attach_widget ()
get_monitor ()
get_reserve_toggle_size ()
get_tearoff_state ()
get_title ()
popdown ()
popup (parent_menu_shell, parent_menu_item, func, data, button, activate_time)
popup_for_device (device, parent_menu_shell, parent_menu_item, func, data, button, activate_time)
reorder_child (child, position)
reposition ()
set_accel_group (accel_group)
set_accel_path (accel_path)
set_active (index)
set_monitor (monitor_num)
set_reserve_toggle_size (reserve_toggle_size)
set_screen (screen)
set_tearoff_state (torn_off)
set_title (title)

Properties

NameTypeFlagsShort Description
accel-groupGtk.AccelGroupr/wThe accel group holding accelerators for the menu
accel-pathstrr/wAn accel path used to conveniently construct accel paths of child items
activeintr/wThe currently selected menu item
attach-widgetGtk.Widgetr/wThe widget the menu is attached to
monitorintr/w/enThe monitor the menu will be popped up on
reserve-toggle-sizeboolr/w/enA boolean that indicates whether the menu reserves space for toggles and icons
tearoff-stateboold/r/wA boolean that indicates whether the menu is torn-off deprecated
tearoff-titlestrd/r/wA title that may be displayed by the window manager when this menu is torn-off deprecated

Signals

NameShort Description
move-scroll

例子

一.MenuBar

这里写图片描述
代码:

#!/usr/bin/env python3
# Created by xiaosanyu at 16/7/4
# section 095
TITLE = "MenuBar"
DESCRIPTION = """
The Gtk.MenuBar is a subclass of Gtk.MenuShell which contains one or more Gtk.MenuItems.
The result is a standard menu bar which can hold many menu items.
"""
import gi

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk


class MenuBarWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="MenuBar Example")
        self.set_border_width(3)
        self.set_size_request(250, 200)
        mb = Gtk.MenuBar()
        filemenu = Gtk.Menu()
        filem = Gtk.MenuItem("File")
        filem.set_submenu(filemenu)
        exit = Gtk.MenuItem("Exit")
        exit.connect("activate", self.on_destroy)
        filemenu.append(exit)
        mb.append(filem)
        vbox = Gtk.VBox(False, 2)
        vbox.pack_start(mb, False, False, 0)
        self.add(vbox)

    def on_destroy(self, widget):
        self.destroy()
        Gtk.main_quit()


def main():
    win = MenuBarWindow()
    win.connect("delete-event", Gtk.main_quit)
    win.show_all()
    Gtk.main()


if __name__ == "__main__":
    main()

代码解析

二.CheckMenu

这里写图片描述

代码

#!/usr/bin/env python3
# Created by xiaosanyu at 16/7/4
# section 091
TITLE = "CheckMenu"
DESCRIPTION = """
A Gtk.CheckMenuItem is a menu item that maintains the state of a boolean value
in addition to a Gtk.MenuItem usual role in activating application code.
"""
import gi

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk


class CheckMenuWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="CheckMenu Example")
        self.set_border_width(3)
        self.set_size_request(250, 200)
        mb = Gtk.MenuBar()
        filemenu = Gtk.Menu()
        filem = Gtk.MenuItem("File")
        filem.set_submenu(filemenu)
        viewmenu = Gtk.Menu()
        view = Gtk.MenuItem("View")
        view.set_submenu(viewmenu)
        stat = Gtk.CheckMenuItem("View Statusbar")
        stat.set_active(True)
        stat.connect("activate", self.on_status_view)
        viewmenu.append(stat)
        exit = Gtk.MenuItem("Exit")
        exit.connect("activate", self.on_destroy)
        filemenu.append(exit)
        mb.append(filem)
        mb.append(view)
        self.statusbar = Gtk.Statusbar()
        self.statusbar.push(1, "Ready")
        vbox = Gtk.VBox(False, 2)
        vbox.pack_start(mb, False, False, 0)
        vbox.pack_start(Gtk.Label(), True, False, 0)
        vbox.pack_start(self.statusbar, False, False, 0)
        self.add(vbox)

    def on_status_view(self, widget):
        if widget.get_active():
            self.statusbar.show()
        else:
            self.statusbar.hide()

    def on_destroy(self, widget):
        self.destroy()
        Gtk.main_quit()


def main():
    win = CheckMenuWindow()
    win.connect("delete-event", Gtk.main_quit)
    win.show_all()
    Gtk.main()


if __name__ == "__main__":
    main()

三.ImageMenu

这里写图片描述
代码

#!/usr/bin/env python3
# Created by xiaosanyu at 16/7/4
# section 092
TITLE = "ImageMenu"
DESCRIPTION = """
A Gtk.ImageMenuItem is a menu item which has an icon next to the text label.
"""
import gi

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk


class ImageMenuWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="ImageMenu Example")
        self.set_border_width(3)
        self.set_size_request(250, 200)
        mb = Gtk.MenuBar()
        filemenu = Gtk.Menu()
        filem = Gtk.MenuItem("_File")
        filem.set_submenu(filemenu)
        agr = Gtk.AccelGroup()
        self.add_accel_group(agr)
        # newi = Gtk.ImageMenuItem(Gtk.STOCK_NEW, agr)  # 这个会有快捷键提示符,没图标
        # newi = Gtk.ImageMenuItem.new_with_label("New") #这个会有快捷键提示符,没图标
        newi = Gtk.ImageMenuItem()
        box = Gtk.Box()
        box.add(Gtk.Image.new_from_icon_name("document-new", Gtk.IconSize.MENU))
        label = Gtk.AccelLabel("New")
        label.set_xalign(0)
        # 必须使用以下两句才能显示快捷键
        label.set_accel_widget(newi)
        box.pack_end(label, True, True, 0)
        newi.add(box)

        newi.connect("activate", self.menu_select, "New")
        key, mod = Gtk.accelerator_parse("<Control>N")
        newi.add_accelerator("activate", agr, key,
                             mod, Gtk.AccelFlags.VISIBLE)
        filemenu.append(newi)

        openm = Gtk.ImageMenuItem()
        box = Gtk.Box()
        box.add(Gtk.Image.new_from_icon_name("document-open", Gtk.IconSize.MENU))
        label = Gtk.AccelLabel("Open")
        label.set_xalign(0)
        # 必须使用以下两句才能显示快捷键
        label.set_accel_widget(openm)
        box.pack_end(label, True, True, 0)

        key, mod = Gtk.accelerator_parse("<Control>O")
        openm.add_accelerator("activate", agr, key,
                              mod, Gtk.AccelFlags.VISIBLE)
        openm.add(box)
        openm.connect("activate", self.menu_select, "Open")
        filemenu.append(openm)
        sep = Gtk.SeparatorMenuItem()
        filemenu.append(sep)

        exit = Gtk.ImageMenuItem()
        box = Gtk.Box()
        box.add(Gtk.Image.new_from_icon_name("application-exit", Gtk.IconSize.MENU))
        label = Gtk.AccelLabel("Quit")
        label.set_xalign(0)
        # 必须使用以下两句才能显示快捷键
        label.set_accel_widget(exit)
        box.pack_end(label, True, True, 0)
        exit.add(box)
        key, mod = Gtk.accelerator_parse("<Control>Q")
        exit.add_accelerator("activate", agr, key,
                             mod, Gtk.AccelFlags.VISIBLE)
        exit.connect("activate", self.on_destroy)
        filemenu.append(exit)
        mb.append(filem)

        vbox = Gtk.VBox(False, 2)
        vbox.pack_start(mb, False, False, 0)
        self.add(vbox)

    @staticmethod
    def menu_select(widget, name):
        print(name, "select")

    def on_destroy(self, widget):
        self.destroy()
        Gtk.main_quit()


def main():
    win = ImageMenuWindow()
    win.connect("delete-event", Gtk.main_quit)
    win.show_all()
    Gtk.main()


if __name__ == "__main__":
    main()

四.MenuPopup

这里写图片描述

代码:

#!/usr/bin/env python3
# Created by xiaosanyu at 16/6/14
# section 093
TITLE = "MenuPopup"
DESCRIPTION = """
Menu.popup()
Displays a menu and makes it available for selection.
"""
import gi

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, Gio

items = ["EditCopy", "EditPaste", "EditSomething"]


class MenuPopupWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="MenuPopup Demo")
        self.set_border_width(10)
        self.set_size_request(250, 200)
        vbox = Gtk.VBox(spacing=6)
        self.add(vbox)
        button = Gtk.Button("button")
        vbox.pack_start(button, False, False, 0)

        menu = Gtk.Menu.new()
        for item in items:
            item = Gtk.MenuItem(label=item)
            item.connect("activate", self.on_menu_selected)
            item.show()
            menu.append(item)
        button.connect("button_press_event", self.my_popup_handler, menu)

    @staticmethod
    def my_popup_handler(window, event, menu):
        if event.type == Gdk.EventType.BUTTON_PRESS:
            if event.button == Gdk.BUTTON_PRIMARY:
                menu.popup(None, None, None, None,
                           event.button, event.time)
                return True

        return False

    @staticmethod
    def on_menu_selected(widget, *args):
        print("Menu item " + widget.get_label() + " was selected")


def main():
    win = MenuPopupWindow()
    win.connect("delete-event", Gtk.main_quit)
    win.show_all()
    Gtk.main()


if __name__ == "__main__":
    main()

这里写图片描述
代码:

#!/usr/bin/env python3
# Created by xiaosanyu at 16/6/16
# section 094
TITLE = "Menus"
DESCRIPTION = """
Menus UI
"""
import gi

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk

UI_INFO = """
<ui>
  <menubar name='MenuBar'>
    <menu action='FileMenu'>
      <menu action='FileNew'>
        <menuitem action='FileNewStandard' />
        <menuitem action='FileNewFoo' />
        <menuitem action='FileNewGoo' />
      </menu>
      <separator />
      <menuitem action='FileQuit' />
    </menu>
    <menu action='EditMenu'>
      <menuitem action='EditCopy' />
      <menuitem action='EditPaste' />
      <menuitem action='EditSomething' />
    </menu>
    <menu action='ChoicesMenu'>
      <menuitem action='ChoiceOne'/>
      <menuitem action='ChoiceTwo'/>
      <separator />
      <menuitem action='ChoiceThree'/>
    </menu>
  </menubar>
  <toolbar name='ToolBar'>
    <toolitem action='FileNewStandard' />
    <toolitem action='FileQuit' />
  </toolbar>
  <popup name='PopupMenu'>
    <menuitem action='EditCopy' />
    <menuitem action='EditPaste' />
    <menuitem action='EditSomething' />
  </popup>
</ui>
"""


class MenuExampleWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="Menu Example")

        self.set_default_size(200, 200)

        action_group = Gtk.ActionGroup("my_actions")

        self.add_file_menu_actions(action_group)
        self.add_edit_menu_actions(action_group)
        self.add_choices_menu_actions(action_group)

        uimanager = self.create_ui_manager()
        uimanager.insert_action_group(action_group)

        menubar = uimanager.get_widget("/MenuBar")

        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        box.pack_start(menubar, False, False, 0)

        toolbar = uimanager.get_widget("/ToolBar")
        box.pack_start(toolbar, False, False, 0)

        eventbox = Gtk.EventBox()
        eventbox.connect("button-press-event", self.on_button_press_event)
        box.pack_start(eventbox, True, True, 0)

        label = Gtk.Label("Right-click to see the popup menu.")
        eventbox.add(label)

        self.popup = uimanager.get_widget("/PopupMenu")

        self.add(box)

    def add_file_menu_actions(self, action_group):
        action_filemenu = Gtk.Action("FileMenu", "File", None, None)
        action_group.add_action(action_filemenu)

        action_filenewmenu = Gtk.Action("FileNew", None, None, Gtk.STOCK_NEW)
        action_group.add_action(action_filenewmenu)

        action_new = Gtk.Action("FileNewStandard", "_New",
                                "Create a new file", Gtk.STOCK_NEW)
        action_new.connect("activate", self.on_menu_file_new_generic)
        action_group.add_action_with_accel(action_new, None)

        action_group.add_actions([
            ("FileNewFoo", None, "New Foo", None, "Create new foo",
             self.on_menu_file_new_generic),
            ("FileNewGoo", None, "_New Goo", None, "Create new goo",
             self.on_menu_file_new_generic),
        ])

        action_filequit = Gtk.Action("FileQuit", None, None, Gtk.STOCK_QUIT)
        action_filequit.connect("activate", self.on_menu_file_quit)
        action_group.add_action(action_filequit)

    def add_edit_menu_actions(self, action_group):
        action_group.add_actions([
            ("EditMenu", None, "Edit"),
            ("EditCopy", Gtk.STOCK_COPY, None, None, None,
             self.on_menu_others),
            ("EditPaste", Gtk.STOCK_PASTE, None, None, None,
             self.on_menu_others),
            ("EditSomething", None, "Something", "<control><alt>S", None,
             self.on_menu_others)
        ])

    def add_choices_menu_actions(self, action_group):
        action_group.add_action(Gtk.Action("ChoicesMenu", "Choices", None,
                                           None))

        action_group.add_radio_actions([
            ("ChoiceOne", None, "One", None, None, 1),
            ("ChoiceTwo", None, "Two", None, None, 2)
        ], 1, self.on_menu_choices_changed)

        three = Gtk.ToggleAction("ChoiceThree", "Three", None, None)
        three.connect("toggled", self.on_menu_choices_toggled)
        action_group.add_action(three)

    def create_ui_manager(self):
        uimanager = Gtk.UIManager()

        # Throws exception if something went wrong
        uimanager.add_ui_from_string(UI_INFO)

        # Add the accelerator group to the toplevel window
        accelgroup = uimanager.get_accel_group()
        self.add_accel_group(accelgroup)
        return uimanager

    @staticmethod
    def on_menu_file_new_generic(widget):
        print("A File|New menu item was selected.")

    def on_menu_file_quit(self, widget):
        self.destroy()
        Gtk.main_quit()

    @staticmethod
    def on_menu_others(widget):
        print("Menu item " + widget.get_name() + " was selected")

    @staticmethod
    def on_menu_choices_changed(widget, current):
        print(current.get_name() + " was selected.")

    @staticmethod
    def on_menu_choices_toggled(widget):
        if widget.get_active():
            print(widget.get_name() + " activated")
        else:
            print(widget.get_name() + " deactivated")

    def on_button_press_event(self, widget, event):
        # Check if right mouse button was preseed
        if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 3:
            self.popup.popup(None, None, None, None, event.button, event.time)
            return True  # event has been handled


def main():
    window = MenuExampleWindow()
    window.connect("delete-event", Gtk.main_quit)
    window.show_all()
    Gtk.main()


if __name__ == "__main__":
    main()




代码下载地址:http://download.csdn.net/detail/a87b01c14/9594728

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sanxiaochengyu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值