简体   繁体   中英

Tkinter check if entry box is empty

How to check if a Tkinter entry box is empty?

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

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

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

This would also work:

if not the_entry_widget.get():
  #do something

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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