问题
I am trying to pass the "filename" from the function on_file_open_clicked
defined as:
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, Pango
UI_INFO = """
<ui>
<menubar name='MenuBar'>
<menu action='FileMenu'>
<menuitem action='FileOpen' />
<menuitem action='FileQuit' />
</menu>
</menubar>
</ui>
"""
class MenuManager(Gtk.UIManager):
def __init__(self):
super().__init__()
action_group = Gtk.ActionGroup("my_actions")
self.add_file_menu_actions(action_group)
self.add_ui_from_string(UI_INFO)
self.insert_action_group(action_group)
def add_file_menu_actions(self, action_group):
action_group.add_actions([
("FileMenu", None, "New"),
("FileOpen", Gtk.STOCK_OPEN, None, None, None,
self.file_open_clicked),
("FileQuit", Gtk.STOCK_QUIT, None, None, None,
self.on_menu_file_quit),
])
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()
print(filename)
elif response == Gtk.ResponseType.CANCEL:
print("Cancel clicked")
dialog.destroy()
def on_menu_file_quit(self, widget):
Gtk.main_quit()
The calling function is defined as:
import gi
import menu
from pybib import parsing_read
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, Pango
class MyWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="mkBiB")
MenuElem = menu.MenuManager()
menubar = MenuElem.get_widget("/MenuBar")
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
box.pack_start(menubar, False, False, 0)
self.add(box)
print(filename)
win = MyWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
obviously, since filename
is not defined in calling function, it is giving error. But I don't know how to retrieve filename from on_file_open_clicked
.
Kindly help.
Edit: Why I need the filename
Since the program pasted above is a minimal one, I have not shown what I will do with the filename
. Actually, the filename is a argument of another routine(that is pure python, nothing to do with gtk3). So, the calling and interface is like:
in main
filename = "../Trial.bib" #I am working with hardcoded file for now
# This is where I need filename from menu.
parsing_read(filename, booklist)
The parsing_read is:
def parsing_read(filename, booklist):
来源:https://stackoverflow.com/questions/34845929/passing-arguments-from-python-gtk-function