Tkinter check if entry box is empty
Asked Answered
P

4

15

How to check if a Tkinter entry box is empty?

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

Ploy answered 16/3, 2013 at 21:51 Comment(0)
A
36

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()
Auxochrome answered 16/3, 2013 at 22:15 Comment(0)
J
7

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
Judejudea answered 17/1, 2016 at 10:52 Comment(0)
E
2

This would also work:

if not the_entry_widget.get():
  #do something
Exhibition answered 26/7, 2014 at 18:36 Comment(0)
E
1

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!

Edmund answered 16/1, 2016 at 18:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.