Python,Tkinter,无法访问StringVar()对象

时间:2015-10-25 09:19:22

标签: python-2.7 tkinter

使用附加的代码我尝试自己访问widget对象中的StringVar对象。

但不幸的是,它说“属性错误:' str'对象没有属性' set'' 知道为什么吗?提前谢谢..

import Tkinter as tk

class mainWindow:
    def __init__(self, master):
        self.master = master

        self.fieldList = {}

        f = tk.Entry(self.master, text='', width = 7)
        f.grid(column=0, row=0)
        self.addToFieldList(f, 'MyFieldA')

    def addToFieldList(self, fieldObj, fieldId):
        fieldObj.bind('<Return>', lambda event, temp=fieldObj :self.commitField(event, temp))

        t = tk.StringVar()  
        fieldObj['textvariable'] = t
        setattr(fieldObj, 'fieldId', fieldId)
        self.fieldList[fieldId] = fieldObj


    def commitField(self, event, sender):
        newValue = sender.get()
        t = sender['textvariable']
        t.set('newValue')  # here comes the error

def main(): 
    root = tk.Tk()
    app = mainWindow(root)

    root.wm_geometry("500x180")
    root.mainloop()

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:0)

将self放在StringVar前面,这样你就可以调用它而不会出错。这是因为它不是全局变量,因此函数无法访问它。同时将t = sender['textvariable']更改为sender['textvariable'] = t