Python GTK 文件保存对话框,如何创建 "Close Without Saving" ResponseType

Python GTK File Save Dialog, How Can I create "Close Without Saving" ResponseType

有时我们需要更多 ResponseType 用于我们程序的对话。例如,当用户关闭文件编辑器时,编辑器会显示对话框让用户选择:"cancel"、"close without saving" "save" 但是 "save" 和 "close without saving" 不会存在于 Gtk.ResponseType 中,因此如何为此创建新的响应类型。这个问题可以用另一种方式解决吗?

谢谢。

Gtk.ResponseType 它是一小组预定义值。这些是负值,而正值(包括零)留给应用程序开发人员根据需要使用。来自 documentation:

Predefined values for use as response ids in Gtk.Dialog.add_button(). All predefined values are negative; GTK+ leaves values of 0 or greater for application-defined response ids.

因此,当您向对话框添加按钮时,您可以使用自己的一组响应值,而不是使用预定义的 Gtk.ResponseType。

让我们采用 this example from the python-gtk3 tutorial 并使用我们自己的响应类型值添加第三个选项:

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

class DialogExample(Gtk.Dialog):

    def __init__(self, parent):
        Gtk.Dialog.__init__(self, "My Dialog", parent, 0,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
             Gtk.STOCK_OK, Gtk.ResponseType.OK, "OPTION 3", 1))

        self.set_default_size(150, 100)

        label = Gtk.Label("This is a dialog to display additional information")

        box = self.get_content_area()
        box.add(label)
        self.show_all()

class DialogWindow(Gtk.Window):

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

        self.set_border_width(6)

        button = Gtk.Button("Open dialog")
        button.connect("clicked", self.on_button_clicked)

        self.add(button)

    def on_button_clicked(self, widget):
        dialog = DialogExample(self)
        response = dialog.run()

        if response == Gtk.ResponseType.OK:
            print("The OK button was clicked")
        elif response == Gtk.ResponseType.CANCEL:
            print("The Cancel button was clicked")
        elif response == 1:
            print("OPTION 3 was clicked")

        dialog.destroy()

win = DialogWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

做了什么?

我们添加了带有标签 OPTION 3 的第三个按钮,其响应 ID 值为 1:

        Gtk.Dialog.__init__(self, "My Dialog", parent, 0,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
             Gtk.STOCK_OK, Gtk.ResponseType.OK, "OPTION 3", 1))

然后,在处理响应时,我们可以检查响应 ID 值并做一些不同的事情:

        ...
            print("The Cancel button was clicked")
        elif response == 1:
            print("OPTION 3 was clicked")
        ...

您可以创建自己的正响应值枚举集并根据需要使用它们(包括零)。祝你好运。

编辑:

在 glade 中,使用按钮时,可以将 response_id 的值设置为整数。它位于小部件的常规设置选项卡中。