Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 802
SkyDrive26 Avatar asked Mar 16 '13 21:03

SkyDrive26


People also ask

How do I check if a text box is empty in Python?

If you wanted to see if it was empty, you could check if there is just one new line. Or, like you are already doing, check if len(t. get("1.0", END) is one.

How do I know if a text widget is empty?

To see if the widget is empty, compare the index right before this newline with the starting index; if they are the same, the widget is empty. You can use the index "end-1c" (or "end - 1 char" ) to represent the index of the character immediately before the trailing newline.

How do I change the size of a button in Python?

In order to customize the Button size, we can use the width and height property of the button widget.


4 Answers

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()
like image 83
Bryan Oakley Avatar answered Nov 08 '22 03:11

Bryan Oakley


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
like image 31
Kenly Avatar answered Nov 08 '22 03:11

Kenly


This would also work:

if not the_entry_widget.get():
  #do something
like image 2
user3787620 Avatar answered Nov 08 '22 05:11

user3787620


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!

like image 1
karlzafiris Avatar answered Nov 08 '22 03:11

karlzafiris