我在 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 个输入参数,即 self
、SimpleAction
和参数
。因此我们需要像这样接受它们:
def file_open_clicked(self, simpleAction, parameter):
现在代码将起作用,因为 self
实际上是一个具有属性 TreeView
的对象。 (仅供引用,Python 中的变量和属性通常以小写形式书写)
关于python - Gio SimpleAction 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35235446/