Python Tkinter 入口 get() [英] Python Tkinter Entry get()

查看:26
本文介绍了Python Tkinter 入口 get()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Tkinter 的 Entry 小部件.我无法让它做一些非常基本的事情:返回输入的值.
有谁知道为什么这样一个简单的脚本不会返回任何东西?我尝试了大量组合,并研究了不同的想法.
此脚本运行但不打印条目:

I'm trying to use Tkinter's Entry widget. I can't get it to do something very basic: return the entered value.
Does anyone have any idea why such a simple script would not return anything? I've tried tons of combinations and looked at different ideas.
This script runs but does not print the entry:

from Tkinter import *
root = Tk()
E1 = Entry(root)
E1.pack()
entry = E1.get()
root.mainloop()
print "Entered text:", entry

看起来很简单.

万一其他人遇到这个问题并且不明白,这就是最终对我有用的东西.我在输入窗口中添加了一个按钮.按钮的命令关闭窗口并执行 get() 函数:

In case anyone else comes across this problem and doesn't understand, here is what ended up working for me. I added a button to the entry window. The button's command closes the window and does the get() function:

from Tkinter import *
def close_window():
    global entry
    entry = E.get()
    root.destroy()

root = Tk()
E = tk.Entry(root)
E.pack(anchor = CENTER)
B = Button(root, text = "OK", command = close_window)
B.pack(anchor = S)
root.mainloop()

这返回了所需的值.

推荐答案

你的第一个问题是 entry = E1.get() 中对 get 的调用甚至发生在你的程序开始之前,很明显 entry 将指向一些空字符串.

Your first problem is that the call to get in entry = E1.get() happens even before your program starts, so clearly entry will point to some empty string.

您最终的第二个问题是无论如何只有在主循环完成后才会打印文本,即您关闭 tkinter 应用程序.

Your eventual second problem is that the text would anyhow be printed only after the mainloop finishes, i.e. you close the tkinter application.

如果要在程序运行时打印 Entry 小部件的内容,则需要安排回调.例如,您可以按如下方式监听 键的按下

If you want to print the contents of your Entry widget while your program is running, you need to schedule a callback. For example, you can listen to the pressing of the <Return> key as follows

import Tkinter as tk


def on_change(e):
    print e.widget.get()

root = tk.Tk()

e = tk.Entry(root)
e.pack()    
# Calling on_change when you press the return key
e.bind("<Return>", on_change)  

root.mainloop()

这篇关于Python Tkinter 入口 get()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆