Tkinter check if entry box is empty

拥有回忆 提交于 2019-12-06 06:21:23

问题


How to check if a Tkinter entry box is empty?

In other words if it doesn't have a value assigned to it.


回答1:


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:

if the_entry_widget.index("end") == 0:
    do_something()



回答2:


If you are using StringVar() use:

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



回答3:


This would also work:

if not the_entry_widget.get():
  #do something



回答4:


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!



来源:https://stackoverflow.com/questions/15455113/tkinter-check-if-entry-box-is-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!