簡體   English   中英

使用 PyGObject 右鍵單擊​​上下文菜單

[英]Right click context menu with PyGObject

我想在用鼠標右鍵單擊時有一個上下文菜單。

有一個關於它的舊 PyGtk 特定問題 但它使用了一個非常舊的 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()

該代碼的結果:當右鍵單擊窗口時,會發生一些事情。 確實會出現一個白色的小矩形。 但它是空的。

在此處輸入圖片說明

你忘了顯示菜單:

    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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM