简体   繁体   English

将绑定事件添加到使用循环创建的输入字段中

[英]Adding Bind Event To Entry Fields Created Using Loops

The main aim here is too bind events to entry fields which are created dynamically using loops and then fetch the values from those fields, how ever i am having issues here to create a function that grabs the text from the entry field as soon as the user starts typing in the box. 这里的主要目的也是将事件绑定到使用循环动态创建的输入字段中,然后从这些字段中获取值,但是我在这里遇到的问题是如何创建一个函数,该函数可以在用户一旦使用时就从输入字段中获取文本开始在框中输入。

from tkinter import Tk, LEFT, BOTH, StringVar
from tkinter.ttk import Entry, Frame
import functools


class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Entry")
        self.pack(fill=BOTH, expand=1)
        self.contents = []
        self.ent = []
        for i in range(0,5):
            self.contents.append(StringVar())

        # give the StringVar a default value
        for i in range(0,5):
            self.entry = Entry(self)
            self.entry.grid(row=0,column=i)
            self.entry["textvariable"] = self.contents[i]
            self.entry.bind('<KeyRelease>', self.on_changed)
            self.ent.append(self.entry)

    def on_changed(self, event):
        print('contents: {}'.format(self.contents.get()))
        return True
def main():
    root = Tk()
    ex = Example(root)
    root.geometry("800x400")
    root.mainloop()


if __name__ == '__main__':
    main()

When you use bind , the event object that is passed to the callback includes a reference to the widget, which you can use to get the value of the entry. 使用bind ,传递给回调的事件对象包括对小部件的引用,您可以使用该小部件获取条目的值。

Example

def on_changed(self, event):
    entry = event.widget
    print('contents: {}'.format(entry.get()))
    return True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM