Python Tkinter 入口 get()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35662844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:46:21  来源:igfitidea点击:

Python Tkinter Entry get()

pythontkintertkinter-entry

提问by Bird

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:

我正在尝试使用 Tkinter 的 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.

这返回了所需的值。

采纳答案by nbro

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

你的第一个问题是对getin的调用entry = E1.get()甚至在你的程序启动之前就发生了,所以很明显entry会指向一些空字符串。

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

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

If you want to print the contents of your Entrywidget 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

如果要Entry在程序运行时打印小部件的内容,则需要安排回调。例如,您可以听听<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()

回答by GANGA SIVA KRISHNA

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