我一直在尝试使用gtk创建一个文件夹选择对话框,但我无法弄清楚如何关闭对话框。这是代码:
from gi.repository import Gtk
import time
dialog = Gtk.FileChooserDialog("Please choose a folder", None,
Gtk.FileChooserAction.SELECT_FOLDER,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
"Select", Gtk.ResponseType.OK))
response = dialog.run()
if response == Gtk.ResponseType.OK:
print("Select clicked")
print("Folder selected: " + dialog.get_filename())
elif response == Gtk.ResponseType.CANCEL:
print("Cancel clicked")
dialog.destroy()
time.sleep(5)
我知道我需要以某种方式调用gtk.main()以使其正常工作,但我无法弄清楚如何操作。 我一直在使用http://python-gtk-3-tutorial.readthedocs.org/en/latest/dialogs.html中的最后一个例子,但是开头有一个框,我不知道如何摆脱它。
答案 0 :(得分:1)
可能有更好的方法,但我通常会这样做:
from gi.repository import Gtk, Gdk, GLib
def run_dialog(_None):
dialog = Gtk.FileChooserDialog("Please choose a folder", None,
Gtk.FileChooserAction.SELECT_FOLDER,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
"Select", Gtk.ResponseType.OK))
response = dialog.run()
if response == Gtk.ResponseType.OK:
print("Select clicked")
print("Folder selected: " + dialog.get_filename())
elif response == Gtk.ResponseType.CANCEL:
print("Cancel clicked")
dialog.destroy()
Gtk.main_quit()
Gdk.threads_add_idle(GLib.PRIORITY_DEFAULT, run_dialog, None)
Gtk.main()
一旦mainloop启动,这将调用run_dialog
函数,这将显示对话框然后退出。
更新:如果要将该代码包含在返回所选文件夹的函数中,则需要将路径保存到非局部变量:
def run_folder_chooser_dialog():
result= []
def run_dialog(_None):
dialog = Gtk.FileChooserDialog("Please choose a folder", None,
Gtk.FileChooserAction.SELECT_FOLDER,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
"Select", Gtk.ResponseType.OK))
response = dialog.run()
if response == Gtk.ResponseType.OK:
result.append(dialog.get_filename())
else:
result.append(None)
dialog.destroy()
Gtk.main_quit()
Gdk.threads_add_idle(GLib.PRIORITY_DEFAULT, run_dialog, None)
Gtk.main()
return result[0]
在python 3中,您可以使用nonlocal result
和result= dialog.get_filename()
代替丑陋的列表引用。