简体   繁体   English

Python Tkinter 入口 get()

[英]Python Tkinter Entry get()

I'm trying to use Tkinter's Entry widget.我正在尝试使用 Tkinter 的 Entry 小部件。 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

Seems so simple.看起来如此简单。

Edit: 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:按钮的命令关闭窗口并执行 get() 函数:

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()

And that returned the desired value.这返回了所需的值。

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.您的第一个问题是在entry = E1.get()调用get in entry = E1.get()甚至在您的程序启动之前就发生了,因此很明显entry将指向一些空字符串。

Your eventual second problem is that the text would anyhow be printed only after the mainloop finishes, ie you close the tkinter application.您最终的第二个问题是无论如何只有在主循环完成后才会打印文本,即您关闭 tkinter 应用程序。

If you want to print the contents of your Entry widget while your program is running, you need to schedule a callback.如果要在程序运行时打印Entry小部件的内容,则需要安排回调。 For example, you can listen to the pressing of the <Return> key as follows例如,您可以按如下方式收听<Return>键的按下

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()
from tkinter import *
import tkinter as tk
root =tk.Tk()
mystring =tk.StringVar(root)
def getvalue():
    print(mystring.get())
e1 = Entry(root,textvariable = mystring,width=100,fg="blue",bd=3,selectbackground='violet').pack()
button1 = tk.Button(root, 
                text='Submit', 
                fg='White', 
                bg= 'dark green',height = 1, width = 10,command=getvalue).pack()

root.mainloop()

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

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