用PyGObject右键单击上下文菜单

时间:2019-02-23 23:58:39

标签: python python-3.x gtk pygobject

我希望在使用鼠标右键单击时具有上下文菜单。

有一个old PyGtk-specific question。但是它使用了非常老的gtk版本和不推荐使用的功能。

我不确定PyGObject(Gtk 3. *)是如何实现的。到目前为止,这是我尝试过的:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Gdk


class MyWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self)
        self.resize(100, 100)

        self._build_context_menu()

        # button event
        self.connect('button-press-event', self._on_button_press_event)

        # close event
        self.connect('delete-event', self._on_delete_event)

    def _build_context_menu(self):
        self.cmenu = Gtk.Menu.new()
        self.cm_item = Gtk.MenuItem.new_with_label('label')
        self.cmenu.append(self.cm_item)

    def _on_delete_event(self, a, b):
        Gtk.main_quit()

    def _on_button_press_event(self, widget, event):
        if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 3:
            self.cmenu.popup_at_pointer()

        return True # event was handled

if __name__ == '__main__':
    window = MyWindow()
    window.show_all()
    Gtk.main()

该代码的结果:在窗口上单击鼠标右键时,发生了某些事情。会出现一个小的白色矩形。但是它是空的。

enter image description here

1 个答案:

答案 0 :(得分:1)

您忘了显示菜单:

    def _build_context_menu(self):
        self.cmenu = Gtk.Menu.new()
        self.cm_item = Gtk.MenuItem.new_with_label('label')
        self.cmenu.append(self.cm_item)
        self.cmenu.show_all()