python - Gio SimpleAction 调用函数

标签 python gtk3 gio

我在 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 。 但我不知道怎么办。 请帮忙

最佳答案

让我为您分解您的代码。

#in main file
MenuElem = menu.MenuManager

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

#in main file
MenuElem = menu.MenuManager()

那么下一个出错的部分就在这里:

def file_open_clicked(self, widget):

如果我们检查 docs对于 activate 信号,我们看到它有 2 个参数。因此,当前在没有初始化对象的情况下,将 self 设置为第一个参数,即 SimpleAction,并将 widget 设置为激活参数.

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

def file_open_clicked(self, simpleAction, parameter):

现在代码将起作用,因为 self 实际上是一个具有属性 TreeView 的对象。 (仅供引用,Python 中的变量和属性通常以小写形式书写)

关于python - Gio SimpleAction 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35235446/

相关文章:

python - cPickle.load 在 Python 中抛出 ImportError

python - 类和外部方法调用

css - GTK+ CSS 阴影脚本函数

python - 在 python 中迭代带有子节点的 GTK3 Treestore

c - GIO网络传输丢失数据

python - 在 Windows 上使用 Glib 观察套接字将它们置于非阻塞模式

python - 我使用 Gio GFile Monitor_file 是否错误?

python - Kivy - 如何从带/不带修饰符的按键中获取正确的字符?

获取序列的第一个和最后一个元素的 Pythonic 方法

python - GTK3 Python 更改单个按钮颜色