关于“Python GTK向组合框添加信号”的问题/于2010年4月24日18:21回答

时间:2011-04-07 22:19:44

标签: python pygtk

我是Python和pygtk的新手,我想使用组合的更改值

在主窗口中,但我不能!

我需要一些帮助

提前致谢

祝你好运

1 个答案:

答案 0 :(得分:1)

没有代码,肯定很难提供帮助,但我会对此进行抨击......

根据您的问题,我猜您想要在用户更改后检索组合框的值。

您将需要创建一个新的事件处理程序,以便在用户更改时检索该值。为了确保整个模块可以使用这些数据,我们首先在模块的TOP处创建一个全局变量。 这必须高于和超出所有类别和定义!

combo_value = -1

在这里,我们创建了一个名为“combo_value”的变量,并将其值设置为-1。这很重要,因为首先,它将变量定义为类型“整数”,其次,如果组合框中未选择任何内容,则“-1”是下面代码返回的值。

现在,在你有pygtk代码的类中,输入这个定义。我更喜欢将所有事件处理程序放在“__ init __”定义中,因为它使它们更容易访问。

def combo_changed(event, data=None):
    #This imports the combo_value variable declared above. Otherwise, the module 
    #would be creating a local variable instead, which would be of no use to the
    #rest of the program.
    global combo_value

    #This retrieves the combo box's selected index and sets the combo_value
    #variable to that index.
    combo_value = combobox.get_active()

现在我们需要使用“已更改”信号将我们的组合框连接到此事件。

combobox.connect("changed", combo_changed)

你有它!然后,您可以通过检查combo_value变量的值来挂接所有其他进程。请记住 - 此代码将该变量设置为组合框中所选项目的INDEX,而不是文本值!这一点非常重要,因为如果您尝试检查字符串中的这个变量,它会让你无处可去。

如果未选择任何内容,则值将为“-1”。请记住从零开始计算所有商品的索引。记下组合框及其索引的值可能很有用,以供参考。它可能看起来像这样:

  

Combobox(选择颜色)   “黑色” - 0   “白色” - 1   “红色” - 2   “绿色” - 3   “蓝色” - 4

然后,在使用组合框值的代码中,你可能会有这样的东西:

if combo_value == -1:
   pass
   #In other words, do nothing at all.
elif combo_value == 0
   #Set color to black
elif combo_value == 1
   #Set color to white

等等,等等。

所以你可以在上下文中看到所有内容,这里是整个代码,减去我上面的小例子......

combo_value = -1

class MyApplication:
   def __init__(self):
       #Your code here.
       def combo_changed(event, data=None):
           #This imports the combo_value variable declared above. Otherwise, the module 
           #would be creating a local variable instead, which would be of no use to the
           #rest of the program.
           global combo_value

           #This retrieves the combo box's selected index and sets the combo_value
           #variable to that index.
           combo_value = combobox.get_active()

       #Your GUI code is here.

       #This is where your combobox is created from a model (we're assuming it is
       #already declared before this point, and called "MyModel".
       combobox = gtk.ComboBox(MyModel)

       #Now we connect the "changed" signal of the combobox to the event we created.
       combobox.connect("changed", combo_changed)

我希望这有帮助!同样,没有代码,很难给你具体细节。我正在帮助你,因为你是新来的,但请务必在未来的所有问题上发布项目中的具体示例和代码。

干杯!