首页 > 解决方案 > 如何允许在 Gtk.FileChooserDialog 中单击鼠标?

问题描述

Gtk.FileChooserDialog下面是我改编自Gtk 文档的小部件的简化示例代码。要选择文件或文件夹或激活此小部件中的任何内容,目前我必须将鼠标指针放在项目上并双击它。相反,我希望使用鼠标单击来进行选择和激活。如何为此小部件进行设置?

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class FileChooserWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="FileChooser Example")

        box = Gtk.Box(spacing=6)
        self.add(box)

        button1 = Gtk.Button("Choose File")
        button1.connect("clicked", self.on_file_clicked)
        box.add(button1)

    def on_file_clicked(self, widget):
        dialog = Gtk.FileChooserDialog("Please choose a file", self,
            Gtk.FileChooserAction.OPEN,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
             Gtk.STOCK_OPEN, Gtk.ResponseType.OK))

        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            print("Open clicked")
            print("File selected: " + dialog.get_filename())
        elif response == Gtk.ResponseType.CANCEL:
            print("Cancel clicked")

        dialog.destroy()


win = FileChooserWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()

标签: python-3.xgtk3pygtk

解决方案


您可以像这样使用"selection-changed"信号

def selection_changed (filechooser, udata):
    print ("selected ", filechooser.get_filename()) # GtkFileChooser method
    if True:                                        # some selection checking
        filechooser.response(Gtk.ResponseType.OK)   # GtkDialog method

dialog = Gtk.FileChooserDialog(...)
dialog.connect ("selection-changed", selection_changed, None)
response = dialog.run()
if response == Gtk.ResponseType.OK:
    pass
elif response == Gtk.ResponseType.CANCEL:
    pass
dialog.destroy()

但是每次用户与文件选择器交互时都会发出此信号,即使用户使用面包屑按钮更改文件夹也是如此。由您决定是否该回复“确定”、“取消”或根本不回复。

此外,用户可能会感到困惑,需要按下的对话框OkEnter实际上在所有其他应用程序中的行为在您的应用程序中表现不同。


推荐阅读