Home > Blockchain >  Tkinter adding entries to database when fields are empty
Tkinter adding entries to database when fields are empty

Time:10-09

I'm trying to prevent users from entering a form in tkinter if an entry field is left blank, by adding a message box informing the user that entries cannot be left blank. However, when a user does leave blanks and presses 'submit', the first error box pops up saying you cant leave blanks, but then it still adds values with blanks to my database and then a follow up popup box says that a player has been added to a database. How do I fix my code so that players are only added to the database if there are no blanks. Below is my code. Thanks

def CreatePlayerProfile():  
conn = sqlite3.connect("PlayersDatabase.db")  
c = conn.cursor()   

c.execute("""CREATE TABLE IF NOT EXISTS Players (
    First_name text,
    Last_name text,
    Age text,
    Matches Played text,
    Goals text,
    Assists text,
    Position text

    )""")   

global firstname
global surname
global age
global matches_played
global goals
global assists
global positionn

firstname = firstname_entry.get()
surname = surname_entry.get()
age = age_entry.get()
matches_played = matches_played_entry.get()
goals = goals_entry.get()
assists = assists_entry.get()
positionn = position.get()

if firstname == "" or surname == "" or age == "" or matches_played == "" or goals == "" or assists == "":
    messagebox.showerror("Error", "Fields cannot be left blank!")         
c.execute('SELECT * FROM Players WHERE First_name ==?',(firstname,))
if c.fetchall():
     messagebox.showerror("Error", "User already exists. Did you mean to update?")
else:
    c.execute("INSERT INTO Players (First_name, Last_name, Age, Matches, Goals, Assists, Position) VALUES (?,?,?,?,?,?,?)",(firstname, surname, age, matches_played, goals, assists, positionn))
    conn.commit()
    messagebox.showinfo("Success!", firstname   " "   surname   " has been added successfully!")

CodePudding user response:

This behavior is according to your code. You check for blanks and display an error messoge messagebox.showerror, but you do nothing to terminate code execution passed this message. I suppose, you can place all that code starting from the SELECT query in an ELSE clause to you check for blanks.

  • Related