Reputation: 109
I am trying to write a function through Tkinter with the following outcome: User types in some input and submits An outcome Label appears below the button as a result When a new input is added in the Entry when the user submits the previous labels is destroyed and only the new result label appears.
I have searched several answers but I was unsuccessful in reaching my goal as with the current code below if a user submits several inputs there will be several labels appearing and when the reset button is clicked only the very last label is deleted while the previous labels still appear.
Here is what I have tried:
root = Tk()
root.title("Search")
root.geometry("400x400")
greeting= Label(root, text="Hi, Please insert input" )
greeting.pack()
search=[]
e = Entry(root, width=50)
e.pack(padx=50)
def myClick(event=None):
global mySubmit
global reply
mySubmit=Label(root, text=results())
search.append(e.get())
print(search)
e.delete(0,"end")
mySubmit.pack()
def results():
global result
if e.get()=="":
result = "Please Insert inquiry"
return result
else:
result = "www.reply.com"
return result
def reset():
global mySubmit
mySubmit.destroy()
mySubmit = Label()
root.bind('<Return>', myClick)
myButton= Button(root, text="Submit", command=myClick)
myButton.pack()
bt2=Button(root,text='RESET',bg='lightblue',command=reset)
bt2.pack()
root.mainloop()
Upvotes: 1
Views: 372
Reputation: 838
Use winfo_ismapped()
to know if that widget is already created or not. Pack it only when it is not already there.
from tkinter import *
root = Tk()
root.title("Search")
root.geometry("400x400")
greeting= Label(root, text="Hi, Please insert input" )
greeting.pack()
search=[]
e = Entry(root, width=50)
e.pack(padx=50)
def myClick(event=None):
global mySubmit
global reply
search.append(e.get())
print(search)
e.delete(0,"end")
if(not mySubmit.winfo_ismapped()): #make a widget only if the mySubmit label is not mapped (created) till now
mySubmit.pack()
def results():
global result
if e.get()=="":
result = "Please Insert inquiry"
return result
else:
result = "www.reply.com"
return result
mySubmit=Label(root, text=results()) #declare it here outside the function scope
def reset():
global mySubmit
mySubmit.destroy()
mySubmit = Label()
root.bind('<Return>', myClick)
myButton= Button(root, text="Submit", command=myClick)
myButton.pack()
bt2=Button(root,text='RESET',bg='lightblue',command=reset)
bt2.pack()
root.mainloop()
Upvotes: 1