How to check if a Tkinter entry box is empty?
In other words if it doesn't have a value assigned to it.
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.
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.
In order to customize the Button size, we can use the width and height property of the button widget.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With