tkinter小部件回调以识别小部件的详细信息

时间:2017-10-17 01:37:26

标签: python-3.x tkinter

我正在阅读http://infohost.nmt.edu/tcc/help/pubs/tkinter/tkinter.pdf 并开始玩" 54.7。额外的争论技巧"位于文档的末尾。如果我理解正确,我可以在列表中创建小部件,这样当单击小部件时,回调应该能够显示存储在实例化类中的信息,我得到要显示的小部件,但是回调没有显示我期望的信息。 IE创建的对象的属性 - 希望有人可以提供帮助。提前谢谢

这是代码

from tkinter import *
class Component(object):
    def __init__(self, image=None, Number=None, Name=None):
        self.image=image
        self.Number=Number
        self.Name=Name

ComponentList = []     #array of componenents

def FeederCB(event):
    print(event.widget.Number, event.widget.Name)

root = Tk()

test=Frame(root, bg='white')
test.grid()

for x in range(0, 2):
    print(x)
    ComponentList.append(Component(None, str(x),"Poly 23"))
    Temp=Label(test, text=ComponentList[-1].Name)
    Temp.configure(bg='white', font='times 12')
    Temp.grid(row=0, column=x, sticky=S)
    ComponentList[-1].image = (Label(test, text='test'))
    ComponentList[-1].image.configure(bg='white')
    ComponentList[-1].image.bind("<Button-1>",FeederCB)
    ComponentList[-1].image.grid(row=1, column=x)
print('Lenght of Component List ', len(ComponentList))
root.mainloop()

1 个答案:

答案 0 :(得分:0)

我想我明白了

from tkinter import *
class Component(object):
    def __init__(self, image=None, Number=None, Name=None):
        self.image=image
        self.Number=Number
        self.Name=Name

ComponentList = []     #array of componenents
#ComponentList.append(Class object,class attibutes)
#example   ComponentList.append(Virgin("1", "materialtype", "Name", "Setpoint"))
#print(ComponentList[0].Name)


def __FeederCB(event, x):
    print(ComponentList[x].Number, ComponentList[x].Name)

root = Tk()

test=Frame(root, bg='white')
test.grid()

for x in range(0, 2):
    print(x)
    ComponentList.append(Component(None, str(x),"Poly 23"))
    Temp=Label(test, text=ComponentList[-1].Name)
    Temp.configure(bg='white', font='times 12')
    Temp.grid(row=0, column=x, sticky=S)
    ComponentList[-1].image = (Label(test, text='test'))
    ComponentList[-1].image.configure(bg='white')
    def FeederCB(event, x=x):
        return __FeederCB(event, x)
    ComponentList[-1].image.bind("<Button-1>",FeederCB)
    ComponentList[-1].image.grid(row=1, column=x)
print('Lenght of Component List ', len(ComponentList))
root.mainloop()