2

我在 Gtk3 应用程序中使用 Gio 操作制作了菜单。菜单项创建为:

#in main file
MenuElem = menu.MenuManager
# Open Menu
action = Gio.SimpleAction(name="open")
action.connect("activate", MenuElem.file_open_clicked)
self.add_action(action)

file_open_clicked, menu.py,class MenuManager中定义为:

import gi
import pybib
import view
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk


class MenuManager:
    def __init__(self):
        self.parsing = pybib.parser()
        self.TreeView = view.treeview()
    #file_open_clicked
    #in menu.py
    def file_open_clicked(self, widget):
        dialog = Gtk.FileChooserDialog("Open an existing fine", None,
                                       Gtk.FileChooserAction.OPEN,
                                       (Gtk.STOCK_CANCEL,
                                        Gtk.ResponseType.CANCEL,
                                        Gtk.STOCK_OPEN, Gtk.ResponseType.OK))
        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            filename = dialog.get_filename()
            dialog.destroy()
            self.TreeView.bookstore.clear()
            self.TreeView.viewer(self.parsing.booklist)
            # self.TreeView.view.set_model()
        elif response == Gtk.ResponseType.CANCEL:
            print("Cancel clicked")
            dialog.destroy()

我收到错误:

Traceback (most recent call last):
  File "/home/rudra/Devel/mkbib/Python/src/menu.py", line 81, in file_open_clicked
    self.TreeView.bookstore.clear()
AttributeError: 'SimpleAction' object has no attribute 'TreeView'

我知道SimpleAction还有一个选择,TreeView应该被调用。但我不知道怎么做。请帮助

4

2 回答 2

2

让我为你分解你的代码。

#in main file
MenuElem = menu.MenuManager

在这里你设置MenuElem指向menu.MenuManager类。可能您打算在此处初始化对象,使其MenuElem成为该类的实例menu.MenuManager这样类的__init__函数就MenuManager被调用了。因此代码应该是:

#in main file
MenuElem = menu.MenuManager()

然后出现问题的下一部分在这里:

def file_open_clicked(self, widget):

如果我们检查文档中的activate信号,我们会看到它有 2 个参数。所以目前没有初始化的对象self被设置为第一个参数,即SimpleAction设置widget为activation parameter

但是由于我们现在已经初始化了MenuManager对象,该file_open_clicked函数将获得 3 个输入参数,即self,SimpleActionparameter。因此,我们需要像这样接受它们:

def file_open_clicked(self, simpleAction, parameter):

现在代码将像self实际上具有属性的对象一样工作TreeView。(仅供参考,Python 变量和属性通常用小写字母编写)

于 2016-02-06T10:50:52.237 回答
1

您的问题是该TreeView属性仅存在于MenuManager类中,而当您调用该file_open_clicked方法时,第一个参数 ( self) 是SimpleAction创建的对象。使用实例file_open_clicked的方法可以解决这个问题。MenuManager

menu_manager = MenuManager()
action = Gio.SimpleAction(name="open")
action.connect("activate", menu_manager.file_open_clicked)
于 2016-02-06T00:34:06.460 回答