python tkinter entry_Python Tkinter Entry get()

问题

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

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:

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.

回答1:

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.

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

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 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("", on_change)

root.mainloop()

回答2:

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

来源:https://stackoverflow.com/questions/35662844/python-tkinter-entry-get

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值