在for循环中创建的组合框中的python tkinter引用

时间:2015-02-26 06:39:14

标签: python for-loop combobox reference tkinter

到目前为止我的代码,我想根据组合框选择导入图像。我需要引用self.box。例如self.box1,self.box2等,或者如果可能的话,以某种方式从循环中将它们附加到某处

from Tkinter import *
import ttk


class Application(Frame):
    def __init__(self, master):
        Frame.__init__(self, master, relief="sunken", border=1)
        self.master = master
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        for i in range(9):
            self.box = ttk.Combobox(self, state="readonly")
            self.box["values"] = ("apple", "bannana", "cherry", "raspberry", "blueberry", "lemon", "tomato", "potato",
                                  "None")
            self.box.grid(row=1+i, column=2, pady=1, padx=1, sticky=E+W+N+S)
            self.box.current(i)
            self.box.bind("<<ComboboxSelected>>", self.change_icon)
            print self.box["values"][i]


    def change_icon(self, event):
        self.var_Selected = self.box.current()
        print "The user selected value now is:"
        print self.var_Selected

root = Tk()
root.title("Random title")
root.geometry("500x250")
app = Application(root)
root.mainloop()

1 个答案:

答案 0 :(得分:0)

您可以让您的应用程序保留一个dict对象(或列表,但实现与索引高度相关),将您的框存储在dict中,并以i为关键:

class Application(Frame):
    def __init__(self, master):
        Frame.__init__(self, master, relief="sunken", border=1)
        # Various initialization code here
        self.box_dict = {}

    def create_widgets(self):
        for i in range(9):
            box = ttk.Combobox(self, state="readonly")
            # Do various things with your box object here
            self.box_dict[i] = box
            # Only complication is registering the callback
            box.bind("<<ComboboxSelected>>",
                         lambda event, i=i: self.change_icon(event, i))


    def change_icon(self, event, i):
        self.var_Selected = self.box_dict[i].current()
        print "The user selected value now is:"
        print self.var_Selected

然后通过self.box_dict[0]等访问这些框

修改我对bindchange_icon方法进行了更新,让每个框在触发事件时将其索引号发送到change_icon Edit2 更改了实施以使用dict代替list,这似乎更加强大。