I am using Tkinter to make a user input form and take values from users and storing the values in a database when clicked on the submit button. I want to clear all the fields from the entry widgets after clicking the submit button so that the values get stored in the database as well as the entry widgets clear out so that the user can again fill the details. I tried the delete(0;'end') command but it did not work.
Following is my code:
def database():
customer_name = name.get()
mobile_no = num.get()
email_id = mail_id.get()
address = addr.get()
result = {
"Customer Name":customer_name,
"Mobile":mobile_no,
"Email ID":email_id,
"Address":address
}
print(result)
db.Customer_Info.insert_one(result)
print('Value Inserted')
client.close()
##Creating tkinter window
def main_page():
global window
window = Tk()
window.title('Products')
window.geometry('400x500')
global name,uname,mob,num,mail_id,addr
name = StringVar()
num = IntVar()
num.set('')
mail_id = StringVar()
addr = StringVar()
Label(window,text = 'HN Organics',background = 'green',
foreground = 'white',font = ('Arial',20)).grid(column = 0,
row = 0, padx = 120, pady =25)
Label(window ,text = "Name").grid()
uname = Entry(window,textvariable = name).grid()
Label(window ,text = "Mobile No.").grid()
mob = Entry(window,textvariable = num).grid()
Label(window ,text = "Email ID").grid()
mail = Entry(window,textvariable = mail_id).grid()
Label(window ,text = "Address").grid()
addr1 = Entry(window,textvariable = addr).grid()
Button(window,text = 'Submit',command = database).grid()
window.mainloop()
main_page()
When the submit button is clicked the values are stored in the database but I want the entries to clear as well after being stored in the database. How do I do that??
I tried using name.delete(0.'end') / name.delete(0.'END') and even name.delete(0.'Tkinter.END') but it shows that there is no attribute delete.
You can add the set('') command in the database function after you store the values and it will clear out the entries so that the user can fill details again.
Just add:
name.set('')
num.set('')
mail_id.set('')
addr.set('')
after client.close()
Don't put quotations around END.
try name.delete (0, END).
Delete is part of normal tkinter library so should work.
Related
I am defining a StringVar() and giving it a value, then using it as the textvariable of an Entry widget. I have also added a trace to the StringVar so that I can use it as a placeholder checker and make the placeholder a different colour to the typed text.
However, when I run the code the entry widget contains no text, but if I print the value of the StringVar() it gives the correct value. Also, the trace command is never called and when I print the value of the textvariable of the Entry widget, it comes out as PY_VAR#.
Does anyone know why this is not working and how to solve it?
circleVarEmailAddress = StringVar()
circleVarEmailAddress.set("email address")
circletextEmailAddress = Entry(forgottenWindow, textvariable = circleVarEmailAddress,
font = 10, relief = "raised", highlightbackground = "black",
borderwidth = 2, fg = "#808080")
circletextEmailAddress.place(x = 75, y = 100, width = 250, height = 50)
def placeholderEmailAddress(a, b, c):
print("Hey")
for i in range(1, 13):
if("email address"[:i] in circleVarEmailAddress.get() == True and
"email address"[i:] in circleVarEmailAddress.get() == True):
index1 = circleVarEmailAddress.get().index("email address"[:i])
index2 = circleVarEmailAddress.get().index("email address"[i:])
circleVarEmailAddress.set(circleVarEmailAddress.get()[:index1] +
circleVarEmailAddress.get()[index1 + i:index2] +
circleVarEmailAddress.get()[index2 + 13 - i:])
if(circleVarEmailAddress.get() != "email address" and
"email address" in circleVarEmailAddress.get() == True):
circleVarEmailAddress.set(circleVarEmailAddress.get().replace("email address", ""))
if circleVarEmailAddress.get() == "":
circleVarEmailAddress.set("email address")
if circleVarEmailAddress.get() == "email address":
circletextEmailAddress.config(fg = "#808080")
else:
circletextEmailAddress.config(fg = "#000000")
circleVarEmailAddress.trace_add("write", placeholderEmailAddress)
Your code runs fine for me if I add some boilerplate.
I assume from the variable name "forgottenWindow" that this is a new window in your program. The problem you are seeing can happen if you use Tk() to make additional windows. Always use Toplevel to make new windows beyond your first one.
forgottenWindow = Toplevel()
I'm trying to create a feedback form using Tkinter in Python. For now I am writing for it to show a message box if the name entry is '' when clicked on the submit button. But the button cannot be clicked and is disabled. How can I fix this?
# import all functions from the tkinter
from tkinter import *
from tkinter import messagebox
# import messagebox class from tkinter
from tkinter import messagebox
# Create a GUI window
root = Tk()
# create a function to check input
def check_input():
if name_input == '':
messagebox.showerror("please enter your name")
# create the input entry
name_input = Entry(root)
age_input = Entry(root)
phone_input = Entry(root)
email_input = Entry(root)
# label the input entry
name_label = Label(text="Username")
age_label = Label(text="Age")
phone_label = Label(text="Phone")
email_label = Label(text="Email")
# display the input entry
name_label.grid(row = 1,column = 1, padx = 10)
name_input.grid(row = 2,column = 1,padx = 10)
age_label.grid(row = 3,column = 1,padx = 10)
age_input.grid(row = 4,column = 1,padx = 10)
phone_label.grid(row = 5,column = 1,padx = 10)
phone_input.grid(row = 6,column = 1,padx = 10)
email_label.grid(row = 7,column = 1,padx = 10)
email_input.grid(row = 8,column = 1,padx = 10)
# create the submit button
submit_button = Button(root,text="Submit",command = check_input)
# display the submit button
submit_button.grid(row = 9,column = 1,padx = 10)
# Start the GUI
root.mainloop()
You have to use the get() method to get contents from an Entry:
# create a function to check input
def check_input():
if name_input.get() == '':
messagebox.showerror("please enter your name")
[![tested and shows no error][1]][1]
your button is clickable and is visible ... there maybe some other issue with your requirements but button works
[1]: https://i.stack.imgur.com/JQqH3.png
if you want to get value from the textbox your need to set text variable for entry
like
ttk.Entry(win,textvariable=hexanum).grid(column=1,row=0)
then if you need to get values from text box you'll be doing something like
inhexa=(hexanum.get()) #hexanum is the textvariable associated to entry/textbox
#inhexa is a variable in which the value from get function is stored (if need to store)
do your homework :) feel free to ask
I'm using Tkinter to create a window with an entry field and a button. When the button is pressed and a certain condition is not met, I need my_label2 to show a specific text, in this case 'Not Valid'. Otherwise, I need the my_label2 to be blank. I have the variable label_text inside a function that is called by the button press, but I get an error saying that label_text is not defined. Can someone help me out with this?
root = tk.Tk()
def my_function():
valid = #this variable is either true or false
if valid :
label_text = ''
else :
label_text = 'Not Valid'
my_label = tk.Label(root, text = "Enter text: ")
my_label.grid(row = 0, column = 0)
my_entry = tk.Entry(root)
my_entry.grid(row = 0, column = 1)
my_button = tk.Button(root, text = "Submit", command = my_function)
my_button.grid(row = 1, column = 1)
my_label2 = tk.Label(root, textvariable = label_text)
my_label2.grid(row = 2, column = 1)
root.mainloop()
Tkinter Variables are different from normal variables. To create one:
label_text = tk.StringVar()
Then, rather than assigning to the variable, you nee to use the set method:
label_text.set('')
or
label_text.set('Not Valid')
See: http://effbot.org/tkinterbook/variable.htm
I am using tkinter to create a small GUI for some Python scripts. For this GUI I need a Combobox named combo with three options:
"none" (the user wants to hand in no data)
"constant" (the user wants to hand in only one value)
"adjustable" (the user wants to hand in more than one value)
Depending on the choice done in combo, a different number of entrys should
appear. The first option should show no entry (and delete all "leftover"
entrys), the second one should show only one entry and the third one should show
two entrys. For me it's no problem to create these entrys but I don't know how
to make them disappear. Once they were created they stay until the GUI is
closed.
I tried something like this:
import tkinter as tk
master = tk.Tk()
var1 = tk.StringVar()
var2 = tk.StringVar()
def submit():
if choice.get() == "none": # all entry boxes schould disappear
entry1.destroy()
entry2.destroy()
if choice.get() == "constant": # only 1 entry box schould be visible
entry1 = tk.Entry(master, textvariable = var1)
entry1.grid(column = 0, row = 1)
entry2.destroy()
if choice.get() == "adjustable": # all entry boxes should be visible
entry1 = tk.Entry(master, textvariable = var1)
entry1.grid(column = 0, row = 1)
entry2 = tk.Entry(master, textvariable = var1)
entry2.grid(column = 0, row = 2)
choice = tk.StringVar(value = "none")
combo = ttk.Combobox(master, textvariable = choice, state = "readonly")
combo["values"] = ("none", "constant", "adjustable")
combo.grid(column = 0, row = 0)
action = tk.Button(master, text = "confirm", command = submit)
action.grid(column=1, row=0)
master.mainloop()
But as I said before, once a entry was created it did not disappear anymore. I
also tried entry.grid_forget() insted of entry.destroy() but this also
didn't work.
I also tryed to declare entry1 and entry1 outside of submit() but then I
don't know how to recreate these entrys once they were destroyed.
Thanks to the help of jasonharper I found a solution while working at another script. The code should look something like this:
import tkinter as tk
from tkinter import ttk
master = tk.Tk()
var1 = tk.StringVar()
var2 = tk.StringVar()
def submit():
if choice.get() == "none": # all entry boxes schould disappear
entry1.grid_remove()
entry2.grid_remove()
if choice.get() == "constant": # only 1 entry box schould be visible
entry1.grid(column = 0, row = 1)
entry2.grid_remove()
if choice.get() == "adjustable": # all entry boxes should be visible
entry1.grid(column = 0, row = 1)
entry2.grid(column = 0, row = 2)
choice = tk.StringVar(value = "none")
combo = ttk.Combobox(master, textvariable = choice, state = "readonly")
combo["values"] = ("none", "constant", "adjustable")
combo.grid(column = 0, row = 0)
entry1 = tk.Entry(master, textvariable = var1)
entry2 = tk.Entry(master, textvariable = var2)
action = tk.Button(master, text = "confirm", command = submit)
action.grid(column=1, row=0)
master.mainloop()
Now all entrys are deleted or created when wanted. To delete the text at the entrys You only have to add entry.delete(0,"end").
I hope this will also help others.
I'm having a major issue with my code below. So here's what I'm trying to do.
The user enters certain inputs into the entry fields and the program calculates and displays a corresponding image (loaded in the frame champFrame) and it's description (in spellFrame).
What I want is to replace this image and text every time I click on the Calculate! button so that it shows me a new image and new description based on my new inputs.
However, in its current state, when I enter new input and click the Calculate! button, it just adds the new image below the old one and the old one is still there.
How do I change my code around so that I can replace these old values?
I have heard of using the pack_forget() method but it only hides the previous image, does not remove it so I can replace it with a new one.
from Tkinter import *
from PIL import ImageTk
from Calculation import getHighestScore
from ImageHandler import *
import json
import urllib2
top = Tk()
top.title("LOLSpellEfficiency")
top.geometry("600x600")
def loadInputFields(frame):
AP_Label = Label(frame, text="AP")
AD_Label = Label(frame, text="AD")
CDR_Label = Label(frame, text="CDR")
AP_Label.grid(row=0, column=0)
AD_Label.grid(row=1, column=0)
CDR_Label.grid(row=2, column=0)
AP_Entry = Entry(frame)
AD_Entry = Entry(frame)
CDR_Entry = Entry(frame)
AP_Entry.grid(row=0, column=1)
AP_Entry.insert(0, "0")
AD_Entry.grid(row=1, column=1)
AD_Entry.insert(0, "0")
CDR_Entry.grid(row=2, column=1)
CDR_Entry.insert(0, "0")
return [AP_Entry, AD_Entry, CDR_Entry]
def loadButton(frame, entries):
Enter_Button = Button(frame, text="Calculate!", command = lambda: executeProgram(entries))
Enter_Button.pack(side=TOP)
def executeProgram(entries):
AP = float(entries[0].get())
AD = float(entries[1].get())
CDR = float(entries[2].get())
data = getChampionData()
result = getHighestScore(data, AP, AD, CDR)
champPhoto = ImageTk.PhotoImage(getChampionImage(result[0]))
champLabel = Label(championFrame, image=champPhoto)
champLabel.image = champPhoto
champLabel.pack(side = TOP)
champName = Label(championFrame, text = "Champion: " + result[0])
champName.pack(side = BOTTOM)
spellPhoto = ImageTk.PhotoImage(getSpellImage(result[2]))
spellLabel = Label(spellFrame, image=spellPhoto)
spellLabel.image = spellPhoto
spellText = Text(spellFrame, wrap=WORD)
spellText.insert(INSERT, "Spell: " + result[1] + "\n")
spellText.insert(INSERT, "Spell description: " + result[3] + "\n")
spellLabel.pack(side=TOP)
spellText.pack(side=BOTTOM)
championFrame.pack()
spellFrame.pack()
def getChampionData():
URL = "https://global.api.pvp.net/api/lol/static-data/na/v1.2/champion?champData=all&api_key=8e8904b4-c112-4b0f-bd1e-641649d9e569"
return json.load(urllib2.urlopen(URL))
inputFrame = Frame(top)
inputFrame.pack()
buttonFrame = Frame(top)
buttonFrame.pack()
championFrame = Frame(top)
spellFrame = Frame(top)
championFrame.pack()
spellFrame.pack()
entries = loadInputFields(inputFrame)
loadButton(buttonFrame, entries)
top.mainloop()
Do not create widgets inside of executeProgram. Instead, create them in your main application, and simply change the widgets inside executeProgram.
All widgets have a configure method which lets you change all of the attributes of that widget. For example, to change the image on a label you would do something like this:
champPhoto = ImageTk.PhotoImage(getChampionImage(result[0]))
champLabel.configure(image=champPhoto)
champLabel.image = champPhoto