Click here to Skip to main content
15,882,163 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I was making a simple Tk GUI which greets the user's input name... I need to raise a Input Error when the user would enter a number. The user must enter LETTERS only. Based on what I have tried, only the first name input was being checked not with the last name. What do I add or edit?



Thank you in advanceee..!!

What I have tried:

import tkinter
from tkinter import *
import tkinter.messagebox

root = Tk()
root.geometry("300x130")
root.resizable(0, 0)
root.title("Greeting User")

def button_enter():
    while True:
        item1 = (input1.get())
        item2 = (input2.get())
        name = (item1 + " " + item2)
        for a in name:
            if (a.isalpha() or a.isspace()) or (a.isalpha() and a.isspace()) and (name.isalpha() and name.isspace()):
                greeting = Label(root, text="Hello, " + name + "!")
                greeting.grid(column=1, row=3)
                return True
            else:
                tkinter.messagebox.showinfo('Input Error', 'Numerical value detected. Try again.')
                return False


label1 = Label(root, text="First Name:").grid(row=0)
label2 = Label(root, text="Last Name:").grid(row=1)

input1 = Entry(root, width=30, justify=CENTER)
input1.grid(column=1, row=0)
input1.get()

input2 = Entry(root, width=30, justify=CENTER)
input2.grid(column=1, row=1)
input2.get()

myButton = Button(root, width=10, text="Enter", command=button_enter)
myButton.grid(column=0, row=3)

root.mainloop()
Posted
Updated 27-May-21 20:46pm

1 solution

OR is a condition that combines two boolean inputs:
A = B OR C

if they are both false, it evaluates to false. Otherwise, it evaluates to true.
So if either B or C is true, then A is true regardless of the value of the other.
So in your code:
        for a in name:
            if (a.isalpha() or a.isspace()) or (a.isalpha() and a.isspace()) and (name.isalpha() and name.isspace()):
...
                return True
If the first character in the input is alphabetic, then your function returns True - it does not even look at any other characters and the loop is terminated.
Move the return True to after the loop, and simplify your condition: most of it is irrelevant!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900