【问题标题】:add gtk3 menubar to main window将 gtk3 菜单栏添加到主窗口
【发布时间】:2016-03-11 01:47:43
【问题描述】:

我是 gtk3 的新手,也可能把我的 python 搞砸了。

在我的menu.py 中,我在 xml 中定义了我的菜单栏:

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

UI_INFO = """
<ui>
  <menubar name='MenuBar'>
      <menu action='FileNew'>
        <menuitem action='FileNewStandard' />
      <menuitem action='FileOpenStandard' />
      <menuitem action='FileQuit' />
    </menu>
    <menu action='EditMenu'>
      <menuitem action='EditCopy' />
      <menuitem action='EditPaste' />
    </menu>
    <menu action='ChoicesMenu'>
      <menuitem action='Book'/>
      <menuitem action='Wine'/>
    </menu>
  </menubar>
  <popup name='PopupMenu'>
    <menuitem action='EditCopy' />
    <menuitem action='EditPaste' />
  </popup>
</ui>
"""

class MenuWindow(Gtk.Window):

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

        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")
        # button = Gtk.Button("Open")    # Submit button to write to
        # button.connect("clicked", self.on_button_clicked)


    def add_file_menu_actions(self, action_group):
        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_fileopen = Gtk.Action("FileOpen", None, None, Gtk.STOCK_OPEN)
        action_group.add_action(action_fileopen)
        action_open = Gtk.Action("FileOpenStandard", "_Open",
                                 "Open an existing file", Gtk.STOCK_OPEN)
        # action_open.connect("activate", self.file_open_clicked)
        action_group.add_action_with_accel(action_open, None)

        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),
        ])

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

        action_group.add_radio_actions([
            ("Book", None, "Book", None, None, 1),
            ("Wine", None, "Wine", None, None, 2)
        ], 1, self.on_menu_choices_changed)

    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

我在main 函数中将其称为:

#!/usr/bin/python3
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk
import menu

class MainWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="Collection Manager")

        self.set_default_size(1000, 20)
        self.set_border_width(10)

        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        MenuElem = menu.MenuWindow()
        box.pack_start(MenuElem, False, False, 0)
        self.add(box)
window = MainWindow()
window.connect("delete-event", Gtk.main_quit)
window.show_all()
Gtk.main()

我一定是做错了什么,因为我遇到了错误:

python3 main2.py 

(main2.py:15800): Gtk-WARNING **: Can't set a parent on a toplevel widget


(main2.py:15800): Gtk-CRITICAL **: gtk_widget_destroy: assertion 'GTK_IS_WIDGET (widget)' failed

而不是菜单栏,我得到两个窗口:

请帮忙

编辑:来自 Cilyan 的回复 我收到错误:

 python3 main_mini.py 
Traceback (most recent call last):
  File "main_mini.py", line 24, in <module>
    window = MainWindow()
  File "main_mini.py", line 15, in __init__
    MenuElem = menu.MenuManager()
  File "/home/rudra/Devel/Cmanage/menu.py", line 32, in __init__
    super.__init__()
TypeError: descriptor '__init__' of 'super' object needs an argument

【问题讨论】:

  • 我认为您不能将一个窗口打包到另一个窗口中。正在检查...

标签: python python-3.x gtk3


【解决方案1】:

解释布拉布拉

有一点很重要,当写像class SubClass(BaseClass) 这样的东西时,你extend BaseClass,这意味着SubClass 一个BaseClass 加上了.在您的代码中,这意味着MenuWindowGtk.Window(UI 的一个分离的矩形区域,带有标题栏,可能还有一些小部件)。实际上,您不想将一个窗口打包到另一个窗口中。您想将菜单栏打包到主窗口中。

我的理解是你想把菜单相关的代码封装在它自己的类中,但是你不需要这个类本身就是一个小部件。为此,您通常不需要继承任何东西(*)。但是,由于您的类可能会操纵 GObject 信号,因此您至少应该派生自 GObject.GObject

实用解决方案

不过,我采用了另一种方法。你的MainWindow 需要的只是一个 UIManager。但是一个 UIManager 会为应用程序的目的而专门调整大小,这样MainWindow 代码就不会被菜单相关的任务弄得乱七八糟。我选择直接从Gtk.UIManager 继承并扩展它以包含应用程序所需的一切,并为应用程序创建某种专门的 UIManager。这是我从MenuWindow 更改的内容:

# New base class, new name to better define what it really is (optional)
# Now, our object will be UIManager by itself, and we can extend it
class MenuManager(Gtk.UIManager):

    def __init__(self):
        # Use super, it's much easier and flexible
        super().__init__()

        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)

        # This code comes from the create_ui_manager function.
        # No need to instanciate a Gtk.UIManager, self is the UIManager already
        self.add_ui_from_string(UI_INFO)
        self.insert_action_group(action_group)

然后,除了删除 create_ui_manager 之外,我什么也没做。现在,与MainWindow 的集成略有不同:

class MainWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="Collection Manager")

        self.set_default_size(1000, 20)
        self.set_border_width(10)

        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        # Don't forget to change the class's name
        MenuElem = menu.MenuManager()
        # Code moved from MenuWindow's __init__ function
        menubar = MenuElem.get_widget("/MenuBar")
        # Now you really pack the menubar widget, not a window containing a menu
        box.pack_start(menubar, False, False, 0)
        self.add(box)
        # Come from create_ui_manager. The AccelGroup must be added to the main window, not to the UIManager itself
        self.add_accel_group(MenuElem.get_accel_group())

还有一件事

您可能需要做的最后一件事是on_menu_choices_changedon_menu_others 函数,因为您没有提供代码,所以我无法查看它。这些函数可能会对整个程序产生影响,因此您需要它们访问对您的应用程序的某种反向引用,并可能访问其他 UI 元素,即将打包到MainWindow 中的其他小部件。

一种可能的解决方案是在实例化菜单时传递对MainWindow 对象的引用并保存它,以便回调可以在收到信号时使用它:

class MenuManager(Gtk.UIManager):
    def __init__(self, mainwindow):
        super().__init__()
        self.mainwindow = mainwindow
        # ...

    def on_menu_choices_changed(self, widget, current):
        # For example
        if current.get_name() == "Wine":
            self.mainwindow.set_icon_to_glass_of_wine()
        else:
            self.mainwindow.set_icon_to_book()

# ...

class MainWindow(Gtk.Window):
    def __init__(self):
        # ...
        MenuElem = menu.MenuManager(self)
        # ...

也就是说,当您开始处理更大的应用程序时,切换到更强大的软件设计(例如 Model-View-Controller 架构)会更容易、更简洁。

【讨论】:

  • 您好,感谢您非常详细的回答,但是当我运行它时,我遇到了错误,如问题中的编辑部分所示
  • @BaRud :糟糕,应该是“super()”,抱歉。当我回到家时,我会检查这是否已修复并更新答案。
  • 嗨 Cilyan,作为最后一段,如何在 main 中访问 self.mainwindow.set_icon_to_book() 中的变量?或者,您可以看看stackoverflow.com/questions/34845929/…吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-02
  • 1970-01-01
  • 1970-01-01
  • 2022-08-20
  • 1970-01-01
相关资源
最近更新 更多