2

Currently I'm using Python tkinter to build a GUI that require user to enter the detail into the textbox(txt3)

How do I validate if the textbox is entered. If not entered, should show message "please enter textbox" . If entered, it will go through SaveInDB() to save in database.

def SaveInDB():
    subID=(txt3.get())
    if not (subID is None):
        ...my code here to save to db
    else:
        res = "Please enter textbox"
        message.configure(text= res)`

txt3 = tk.Entry(window,width=20)
txt3.place(x=1100, y=200)

saveBtn = tk.Button(window, text="Save", command=SaveInDB ,width=20 )
saveBtn .place(x=900, y=300)

This code above does not work for me..Please help

5
  • Your code is not clear for me but just checking whether "txt3" is None, is not good method because you wouldn't consider white spaces or unexpected inputs if it is important. Commented Apr 17, 2019 at 5:39
  • @madogan which method do you prefer in order to consider in whitespaces because I want to make the textbox compulsory to be entered Commented Apr 17, 2019 at 5:47
  • @madogan I had already update my code with textbox and button, please help to check what should I do in order to validate the textbox Commented Apr 17, 2019 at 5:58
  • You can use strip() method for this as @Bitto-Bennichan Commented Apr 17, 2019 at 6:04
  • @madogan thank you so much I finally got it worked! :) Commented Apr 18, 2019 at 4:12

1 Answer 1

2

You can check if the entry has any value and if not use showinfo to display a popup message. If you don't want a popup you can simply set the focus like entry.focus() or highlight the background with a different color. A minimal example of what you are trying to accomplish.

import tkinter as tk
from tkinter.messagebox import showinfo

def onclick():
    if entry.get().strip():
        print("Done")
    else:
        showinfo("Window", "Please enter data!")
        #or either of the two below
        #entry.configure(highlightbackground="red")
        #entry.focus()

root = tk.Tk()
entry = tk.Entry(root)
entry.pack()
tk.Button(root, text='Save', command=onclick).pack()
root.mainloop()

Pop up version

enter image description here

Focus version

enter image description here

Background color version

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for the help , finally it's working as I wanted :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.