Python Tkinter 检查输入框是否为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15455113/
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
Tkinter check if entry box is empty
提问by SkyDrive26
How to check if a Tkinter entry box is empty?
如何检查 Tkinter 输入框是否为空?
In other words if it doesn't have a value assigned to it.
换句话说,如果它没有分配给它的值。
采纳答案by Bryan Oakley
You can get the value and then check its length:
您可以获取该值,然后检查其长度:
if len(the_entry_widget.get()) == 0:
do_something()
You can get the index of the last character in the widget. If the last index is 0 (zero), it is empty:
您可以获取小部件中最后一个字符的索引。如果最后一个索引为 0(零),则为空:
if the_entry_widget.index("end") == 0:
do_something()
回答by user3787620
This would also work:
这也可以:
if not the_entry_widget.get():
#do something
回答by atlas
Here's an example used in class.
这是课堂上使用的一个例子。
import Tkinter as tk
#import tkinter as tk (Python 3.4)
class App:
#Initialization
def __init__(self, window):
#Set the var type for your entry
self.entry_var = tk.StringVar()
self.entry_widget = tk.Entry(window, textvariable=self.entry_var).pack()
self.button = tk.Button(window, text='Test', command=self.check).pack()
def check(self):
#Retrieve the value from the entry and store it to a variable
var = self.entry_var.get()
if var == '':
print "The value is not valid"
else:
print "The value is valid"
root = tk.Tk()
obj = App(root)
root.mainloop()
Then entry from above can take only numbers and string. If the user inputs a space, will output an error message. Now if late want your input to be in a form of integer or float or whatever, you only have to cast it out!
然后从上面输入只能取数字和字符串。如果用户输入空格,将输出错误信息。现在,如果后期希望您的输入采用整数或浮点数或其他形式,您只需将其丢弃即可!
Example:
yourVar = '5'
newVar = float(yourVar)
>>> 5.0
Hope that helps!
希望有帮助!
回答by Kenly
If you are using StringVar()use:
如果您正在使用,请StringVar()使用:
v = StringVar()
entry = Entry(root, textvariable=v)
if not v.get():
#do something
If not use:
如果不使用:
entry = Entry(root)
if not entry.get():
#do something

