Binding a lambda function to multiple Tkinter Entry widgets created with For loop [closed]

StackOverflow https://stackoverflow.com/questions/22388337

Вопрос

I am attempting to bind a function to multiple Entry widgets in Tkinter. I populated my frame with many Entry widgets in a for loop. To bind a function to an Entry widget that was created using a for loop, I thought I could do something like the following:

import Tkinter as tk   

class Application(tk.Frame):
    def __init__(self, master):
        self.master = master
        tk.Frame.__init__(self, master, width=200, height=200)
        self.master.title('Application')
        self.pack_propagate(0)
        self.pack()

        for i in range(10):
            strVar = tk.StringVar()
            item = tk.Entry(self, textvariable=strVar)
            item.bind(sequence='<Return>', func=lambda strVar=strVar, i=i: self.obtain(i, strVar))
            item.grid(row=i, sticky=tk.W)

    def obtain(self, i, strVar):
        print i
        print strVar.get()

    def run(self):
        self.mainloop()

app = Application(tk.Tk())
app.run()

But I am obtaining the following error:

print strVar.get()
AttributeError: Event instance has no attribute 'get'

I don't understand why it can't interpret strVar as a tk.StringVar() variable...Any ideas?

Это было полезно?

Решение

The Event is passed as the first argument to your callback. Since your callback's first argument is strVar, the Event object is being passed in that variable. You should add an additionl argument at the front of your argument list to hold the event, e.g., lambda event, strVar=strVar, i=i: self.obtain(i, strVar).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top