2016-03-05 90 views
1

我正在使用PyGtk 2.0。在我的程序中,我創建了一個包含Combobox的對話框。該對話框沒有OK或Cancel按鈕。當組合框中的項目被選中時,對話框必須關閉(意味着在onchange事件中)。但是我不能在沒有手動關閉操作的情況下銷燬對話框。如何關閉組合框事件更改時的GTK對話?

我的相關代碼:

def mostrar_combobox(self, titulo, texto_etiqueta, lista): 
    """ 
    MÃ © All to show a combobox on screen and get the option chosen 
    """ 
    #print texto_etiqueta 
    #dialogo = gtk.Dialog(titulo, None, 0, (gtk.STOCK_OK, gtk.RESPONSE_OK, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)) 
    dialogo = gtk.Dialog(titulo, None, gtk.DIALOG_MODAL, None) 
    etiqueta = gtk.Label(texto_etiqueta) 
    etiqueta.show() 
    dialogo.vbox.pack_start(etiqueta) 
    combobox = gtk.combo_box_new_text() 
    for x in lista: 
     combobox.append_text(x) 
    combobox.connect('changed', self.changed_cb) 
    #combobox.set_active(0) 
    combobox.show() 
    dialogo.vbox.pack_start(combobox, False) 
    response = dialogo.run() 

    elemento_activo = combobox.get_active() 

    return elemento_activo 

    dialogo.hide() 

def changed_cb(self, combobox): 
    index = combobox.get_active() 
    if index > -1: 
     print index 

請告知如何能onchange後關閉的。

我在這裏發表的示例代碼:http://pastie.org/10748579

但我主要的應用程序我無法重現相同。

+2

ANES,我注意到,有5年多問題,你還沒有接受任何答案。我希望你知道,作爲提問者,你有選擇權(和責任)來標記解決你的問題的答案。您可以通過點擊每個答案左側的刻度線來做到這一點,這樣做會爲您和提問者都贏得聲譽。提升和接受答案是你可以感謝那些幫助你的人(提出好的答案,並接受解決你的問題的答案)的方式。 –

回答

1

下面是一個簡單的例子,它可以做你想做的事。我使用你的一些代碼,我寫了幾年的代碼和一些新的東西來構建它。

#!/usr/bin/env python 

''' Create a GTK Dialog containing a combobox that closes 
    when a combobox item is selected 

    See http://stackoverflow.com/q/35812198/4014959 

    Written by PM 2Ring 2016.03.05 
''' 

import pygtk 
pygtk.require('2.0') 
import gtk 

lista = ('zero', 'one', 'two', 'three') 

class Demo: 
    def __init__(self): 
     self.win = win = gtk.Window(gtk.WINDOW_TOPLEVEL) 
     win.connect("destroy", lambda w: gtk.main_quit()) 

     button = gtk.Button("Open dialog") 
     button.connect("clicked", self.dialog_button_cb) 
     win.add(button) 
     button.show() 

     self.dialog = gtk.Dialog("Combo dialog", self.win, 
      gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, 
      (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT)) 

     combobox = gtk.combo_box_new_text() 
     for s in lista: 
      combobox.append_text(s) 
     combobox.connect("changed", self.combo_cb) 
     self.dialog.action_area.pack_end(combobox) 
     combobox.show() 

     win.show() 

    def dialog_button_cb(self, widget): 
     response = self.dialog.run() 
     print "dialog response:", response 
     self.dialog.hide() 
     return True 

    def combo_cb(self, combobox): 
     index = combobox.get_active() 
     if index > -1: 
      print "combo", index, lista[index] 
      self.dialog.response(gtk.RESPONSE_ACCEPT) 
     return True 

def main(): 
    Demo() 
    gtk.main() 


if __name__ == "__main__": 
    main() 

測試上的Python 2.6.6,GTK版本2.21.3

+0

親愛的主席先生, 你的代碼工作太棒了......非常感謝 Anes – Anes