Python check if textbox is not filled - python

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

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
Focus version
Background color version

Related

Tkinter check if something has been input and display error if it has not

I am trying to make sure that a user types something into a tkinter Entry widget. Basically, if they leave the entry field blank, I want the program to display a popup telling them to enter a valid name. However, this code is not working. I think I am not checking if something has been entered correctly. My guess is that I made a mistake around the if statement in the code.
def get_name():
top = Toplevel(root)
label = Label(top, text="Please input your name.")
label.pack()
name = Entry(top)
if name == ""
messagebox.showinfo(title="Error", message="Please enter a valid name.")
else:
pass
name.pack()
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
root.geometry(‘100x100’)
user_entry_var = tk.StringVar()
def validate_user_entry() -> None:
entry = user_entry_var.get()
if entry == “”:
messagebox.showerror(‘Error’, ‘Enter a valid name’)
user_entry = tk.Entry(root, textvariable=user_entry_var).pack()
validate_button = tk.Button(root, text = ‘Check’, command = validate_user_entry).pack()
root.mainloop()
In your code, name is referring to the Entry widget, not the text. To access the text, you would need to use text variables, and use the get() function to access the entry. I’m not sure what you’re making, but hopefully the code above should help.

How do I destroy a tkinter frame?

I am trying to make a tkinter frame that will contain an entry field and a submit button. When the submit button is pressed, I want to pass the entry string to the program and destroy the frame. After many experiments, I came up with this script:
from tkinter import *
from tkinter import ttk
import time
root = Tk()
entryframe = ttk.Frame(root)
entryframe.pack()
par = StringVar('')
entrypar = ttk.Entry(entryframe, textvariable=par)
entrypar.pack()
submit = ttk.Button(entryframe, text='Submit', command=entryframe.quit)
submit.pack()
entryframe.mainloop()
entryframe.destroy()
parval = par.get()
print(parval)
time.sleep(3)
root.mainloop()
When the "Submit" button is pressed, the parameter value is passed correctly to the script and printed. However, the entry frame is destroyed only after 3 seconds (set by the time.sleep function).
I want to destroy the entry frame immediately.
I have a slightly different version of the script in which the entry frame does get destroyed immediately (although the button itself is not destroyed), but the value of par is not printed:
from tkinter import *
from tkinter import ttk
import time
root = Tk()
entryframe = ttk.Frame(root)
entryframe.pack()
par = StringVar('')
entrypar = ttk.Entry(entryframe, textvariable=par)
entrypar.pack()
submit = ttk.Button(root, text='Submit', command=entryframe.destroy)
submit.pack()
entryframe.mainloop()
# entryframe.destroy()
parval = par.get()
print(parval)
time.sleep(3)
root.mainloop()
How can I get both actions, namely the entry frame destroyed immediately and the value of par printed?
Note 100% sure what you are trying to do but look at this code:
from tkinter import *
from tkinter import ttk
def print_results():
global user_input # If you want to access the user's input from outside the function
# Handle the user's input
user_input = entrypar.get()
print(user_input)
# Destroy whatever you want here:
entrypar.destroy()
submit.destroy()
# If you want you can also destroy the window: root.destroy()
# I will create a new `Label` with the user's input:
label = Label(root, text=user_input)
label.pack()
# Create a tkitner window
root = Tk()
# Create the entry
entrypar = ttk.Entry(root)
entrypar.pack()
# Create the button and tell tkinter to call `print_results` whenever
# the button is pressed
submit = ttk.Button(root, text="Submit", command=print_results)
submit.pack()
# Run tkinter's main loop
# It will stop only when all tkinter windows are closed
root.mainloop()
# Because of the `global user_input` now we can use:
print("Again, user_input =", user_input)
I defined a function which will destroy the entry and the button. It also creates a new label that displays the user's input.
I was able to accomplish what I wanted using the wait_window method. Here is the correct script:
from tkinter import *
from tkinter import ttk
root = Tk()
entryframe = ttk.Frame(root)
entryframe.pack()
entrypar = ttk.Entry(entryframe)
entrypar.pack()
submit = ttk.Button(entryframe, text='Submit', command=entryframe.destroy)
submit.pack()
entrypar.wait_window()
parval = entrypar.get()
print(parval)
close_button = ttk.Button(root, text='Close', command=root.destroy)
close_button.pack()
root.mainloop()
My intention was not fully apparent in my original question, and I apologize for that. Anyway, the answers did put me on the right track, and I am immensely thankful.

Python getting User input with Tkinter

In my Python program somehwere in between i pop-up a Tkinter GUI to get user Input. User selects option from a Tkinter.ttk Combobox. From here once the user closes the Tkinter window i want the selection made by user to be used further in the code. But upon close unable to get the user selection back into the code.
Please help.
One way is to create a StringVar() in the root window and then associate it with the Combobox() in the Toplevel() window. The combobox will change the value of the StringVar() and you can read it affter popup window is closed.
from tkinter import *
from tkinter import ttk
root = Tk()
combotext = StringVar()
def get_input():
popup = Toplevel()
box = ttk.Combobox(popup, textvariable=combotext, state='readonly')
box['values'] = ("Camembert", "Brie", "Tilsit", "Stilton")
combotext.set('Choose')
box.pack(padx=20, pady=20)
Button(root, text='Get input', command=get_input).pack(padx=90, pady=10)
Label(root, textvariable=combotext).pack(pady=(0,10))
root.mainloop()

How to close other window by python Tkinter?

I have following python code in Tkinter.
import tkinter as tk
def main_gui(login, s):
login.quit() # close login window
win = tk.Tk()
win.geometry('300x150')
name = tk.Label(win, text='Hello' + s.get()) # Hello David
name.pack()
win.mainloop()
# initial Tkinter frame
login = tk.Tk()
login.title('Login')
login.geometry('300x150')
# input user name
user_name_var = tk.StringVar()
user_name_var.set('David')
tk.Label(login, text='User name').place(x=10, y=50)
user_name = tk.Entry(login, textvariable=user_name_var)
user_name.place(x=100, y=50)
input_ok = tk.Button(win_login, command=lambda: main_gui(login, user_name), text='OK', width=15)
input_ok.place(x=100, y=90)
win_login.mainloop()
I want to close login window, but my code can not close it. How to solve it.
You are almost there - only two details you have to adapt:
The method to remove a widget in Tkinter is destroy, so login.quit() should be login.destroy().
Once login is destroyed, the user_name Entry will also be destroyed, and you will not be able to get the name from it anymore. You should get the name earlier, e.g., directly in the lambda:
... lambda: main_gui(login, user_name.get()), ...
you can use the
root.withdraw()
function, this will close the window without completely destroying all of the root.after functions

How To Let Your Main Window Appear after succesful login in Tkinter(PYTHON 3.6

This is ui which comes with default user name and password but after successful login the main UI needs to appear
Challenge
when you correctly input the user name and password the main window doesn't open but rather when you click cancel or close button then it opens
Finding solution
Main window should appear after successfully login with the default password and user name
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
def try_login(): # this my login function
if name_entry.get()==default_name and password_entry.get() ==
default_password:
messagebox.showinfo("LOGIN SUCCESSFULLY","WELCOME")
else:
messagebox.showwarning("login failed","Please try again" )
def cancel_login(): # exit function
log.destroy()
default_name=("user") #DEFAULT LOGIN ENTRY
default_password=("py36")
log=Tk() #this login ui
log.title("ADMIN-LOGIN")
log.geometry("400x400+400+200")
log.resizable (width=FALSE,height=FALSE)
LABEL_1 = Label(log,text="USER NAME")
LABEL_1.place(x=50,y=100)
LABEL_2 = Label(log,text="PASSWORD")
LABEL_2.place(x=50,y=150)
BUTTON_1=ttk. Button(text="login",command=try_login)
BUTTON_1.place(x=50,y=200)
BUTTON_1=ttk. Button(text="cancel",command=cancel_login)
BUTTON_1.place(x=200,y=200)
name_entry=Entry(log,width=30)
name_entry.place(x=150,y=100)
password_entry=ttk. Entry(log,width=30,show="*")
password_entry.place(x=150,y=150)
log. mainloop()
MAIN_WINDOW=Tk() #after successful this main ui should appear
MAIN_WINDOW.geometry("600x500+300+100")
MENU_1 = Menu(MAIN_WINDOW)
MAIN_WINDOW.config(menu=MENU_1)
SETTINGS_1 = Menu(MENU_1,tearoff=0)
MENU_1.add_cascade(label="SETTINGS",menu=SETTINGS_1,underline=0)
SETTINGS_1.add_command(label="Change Password")
MAIN_WINDOW. mainloop()
I would appreciate if the answers comes in functions as am newbie in python and programming in general
The below code can be used for the desired effect and is commented to show what is happening each step of the way:
from tkinter import * #Imports Tkinter
import sys #Imports sys, used to end the program later
root=Tk() #Declares root as the tkinter main window
top = Toplevel() #Creates the toplevel window
entry1 = Entry(top) #Username entry
entry2 = Entry(top) #Password entry
button1 = Button(top, text="Login", command=lambda:command1()) #Login button
button2 = Button(top, text="Cancel", command=lambda:command2()) #Cancel button
label1 = Label(root, text="This is your main window and you can input anything you want here")
def command1():
if entry1.get() == "user" and entry2.get() == "password": #Checks whether username and password are correct
root.deiconify() #Unhides the root window
top.destroy() #Removes the toplevel window
def command2():
top.destroy() #Removes the toplevel window
root.destroy() #Removes the hidden root window
sys.exit() #Ends the script
entry1.pack() #These pack the elements, this includes the items for the main window
entry2.pack()
button1.pack()
button2.pack()
label1.pack()
root.withdraw() #This hides the main window, it's still present it just can't be seen or interacted with
root.mainloop() #Starts the event loop for the main window
This makes use of the Toplevel widget in order to create a window which asks for the users details and then directs them to the main window which you can setup as you please.
You are also still able to use the pop up messages you have used in your example and if required you can also change the size of the Toplevel widget.
Please be advised however that this is not a particularly secure way of managing passwords and logins. As such I would suggest that you look up the proper etiquette for handling sensitive information in programming.

Categories

Resources