简体   繁体   English

如何将 tkinter Entry 值传递给 Python 中的函数?

[英]How to pass tkinter Entry values to a function in Python?

I want to pass the values in a tkinter Entry box to a function without using a button.我想在不使用按钮的情况下将 tkinter 输入框中的值传递给函数。 How can I so this?我怎么能这样?

I've tried just binding the Entry field but what is passed is not the entry but a KeyPress Event我试过只绑定 Entry 字段,但传递的不是条目而是 KeyPress 事件

import tkinter


def print_entry(entry):
    print(entry)

root = tkinter.Tk()
entry_field = tkinter.Entry(root)
entry_field.pack()
entry_field.bind("<Return>", print_entry)
entry_field.focus()
root.mainloop()

I expect to get the values entered in the Entry box but instead get:我希望得到在输入框中输入的值,但得到:

<KeyPress event state=Mod1 keysym=Return keycode=13 char='\r' x=966 y=186>

I figured out a solution:我想出了一个解决方案:

import tkinter


def print_entry(entry):
    print(entry)


root = tkinter.Tk()
entry_field = tkinter.Entry(root)
entry_field.pack()
entry_field.bind("<Return>", lambda x: print_entry(entry_field.get()))
entry_field.focus()
root.mainloop()

When you bind a function, the function will be passed an argument which represents the event.当您绑定一个函数时,该函数将被传递一个表示事件的参数。 One of the attributes of that argument is widget , which represents the widget that received the event.该参数的属性之一是widget ,它表示接收事件的小部件。

The most common solution is to not pass values into callbacks.最常见的解决方案是将值传递给回调。 Instead, have the callbacks retrieve the information that they need using this object:相反,让回调使用此对象检索它们需要的信息:

def print_entry(event):
    print(event.widget.get())

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

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