One of the issues in your code is use use of the if
statement. You are asking if the Text Object has a length instead of checking the content of the text object. This can be corrected with the use of get()
. If you use get()
on a Text Box you will need to specify the indices. .get(1.0, "end")
. The problem with doing it this way is you will be getting a length that is 1 character longer than what has been typed so the easy fix to this is to just use an entry field here.
With an Entry()
field you can use get()
without indices and it will get a copy of the text in that field. Keep in mind if you have a space before or after the text it will count that as well. If you want to compensate for this you can add strip()
after get()
to delete the white-space on either side.
For a little clean up you will want to change how you are creating your message. With your code if you press the button multiple times then the program will add a new message with each button press. This will cause the messages to stack. To avoid this lets create the message label first and then just update it with our function using the .config()
method.
The next bit of clean up lets remove the variable assignments to widgets that do not need them. Your first label and the button do not need to be assigned to a variable in this case.
The last bit of clean up is making sure you are consistent with your widgets. Right now (based of your example code) you are importing tkinter twice. Once with from tkinter import *
and once with import tkinter as tk
. You do not need both and should stick with the 2nd import method only. Using import tkinter as tk
will help prevent you from overriding build in methods on accident.
Take a look at my below code:
import tkinter as tk
root = tk.Tk()
def check_number():
msg.config(text = "")
if len(txtNum1.get().strip()) != 11:
error_number = "the number that you entered is wrong"
msg.config(text = error_number)
tk.Label(root, text="enter your number", fg="gray").pack()
txtNum1 = tk.Entry(root, width=30)
txtNum1.pack(side=tk.TOP)
tk.Button(root, text="chek", fg="green", command=check_number).pack(side=tk.BOTTOM)
msg = tk.Message(root, text = "" , fg="red")
msg.pack()
root.mainloop()