Python GTK。如何连续显示对话框?

时间:2019-03-08 08:34:13

标签: python gtk

我想在带列表框的自定义对话框上显示对话框。如果在列表框中选择的选项是错误的,则显示消息并允许再次选择正确的答案。我已经编写了此演示代码来演示该问题:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from ListBoxRowWithData import ListBoxRowWithData
import shutil
from InterfaceChooserDialog import InterfaceChooserDialog
import netifaces as ni

class InterfaceChooserDialog(Gtk.Dialog):
    def __init__(self, parent):
        Gtk.Dialog.__init__(self, "Choose interface", parent, 0,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                Gtk.STOCK_OK, Gtk.ResponseType.OK))
        self.connect("response", self.on_response)

        wrapper_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        description_label = Gtk.Label("Select one")
        wrapper_box.pack_start(description_label, False, False, 0)
        self.listbox = Gtk.ListBox()
        strings = ["12", "22", "32"]

        for single_string in strings:
            row = Gtk.ListBoxRow()
            row.string = single_string
            hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50)
            row.add(hbox)
            label = Gtk.Label(single_string, xalign=0)
            hbox.pack_start(label, True, True, 0)
            self.listbox.add(row)

        self.selected_interface = self.listbox.get_row_at_index(0)
        self.listbox.select_row(self.selected_interface)
        wrapper_box.pack_start(self.listbox, False, False, 0)
        box = self.get_content_area()
        box.add(wrapper_box)
        self.show_all()

    def on_response(self, widget, response_id):
        self.selected_one = self.listbox.get_selected_row()

    def get_selected_string(self):
        return self.selected_one.string

class MyWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="Example")
        self.set_default_size(600, 480)
        dialog = InterfaceChooserDialog(self)
        response = dialog.run()
        if response == Gtk.ResponseType.OK: 
            selected_string = dialog.get_selected_string() 
            print("Selected string", selected_string)
            if selected_string == 12: 
                print("selected")
                dialog.destroy()
            else:
                dialog_wrong = Gtk.MessageDialog(self, 0, Gtk.MessageType.INFO,
                        Gtk.ButtonsType.OK, "This is wrong. Select 12")
                dialog_wrong.run()
                dialog_wrong.destroy()


        elif response == Gtk.ResponseType.CANCEL:
            dialog.destroy()


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

但是不允许多次显示自定义对话框。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您需要在末尾运行Gtk.main(),以便主循环开始运行,并且在显示对话框之后程序不会退出。

如果这样做,您可能还想在构造函数中运行win.show(),以使该窗口不会出现在对话框之后。