Python GTK 为组合框添加信号

0 投票
2 回答
3575 浏览
提问于 2025-04-15 21:59

我用PyGTK创建了一个下拉框:

fileAttrCombo = gtk.ComboBox(); 

我想给这个下拉框添加一个信号处理器。这个信号处理器的作用是当用户在下拉框中更改选择时进行处理。

这样做的最佳方法是什么呢?

2 个回答

0

试着把“if index:”换成“if index != None:”,这样可以获取下拉框中第一个值,因为它的索引是0。

2

这个下拉框有一个叫做“changed”的信号。

这里有一个简单的例子,展示了如何使用这个信号。

#!/usr/bin/env python

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

class ComboBoxExample:
    def __init__(self):
        window = gtk.Window()
        window.connect('destroy', lambda w: gtk.main_quit())
        combobox = gtk.combo_box_new_text()
        window.add(combobox)
        combobox.append_text('Select a pie:')
        combobox.append_text('Apple')
        combobox.append_text('Cherry')
        combobox.append_text('Blueberry')
        combobox.append_text('Grape')
        combobox.append_text('Peach')
        combobox.append_text('Raisin')
        combobox.connect('changed', self.changed_cb)
        combobox.set_active(0)
        window.show_all()
        return

    def changed_cb(self, combobox):
        model = combobox.get_model()
        index = combobox.get_active()
        if index:
            print 'I like', model[index][0], 'pie'
        return

def main():
    gtk.main()
    return

if __name__ == "__main__":
    bcb = ComboBoxExample()
    main()

撰写回答