1

I created a button that retrieves a list from a DataFrame based on some input from a text field. Everytime the button is pressed, the list will be refreshed. I output the list (as an OptionMenu) in a separate Frame (outputFrame). However, every time I press this button, a new OptionMenu is added to the Frame (instead of overwriting the previous one). How can I make sure that the content of 'ouputFrame' is overwritten each time I press the button?

# start
root = Tkinter.Tk()

# frames
searchBoxClientFrame = Tkinter.Frame(root).pack()
searchButtonFrame = Tkinter.Frame(root).pack()
outputFrame = Tkinter.Frame(root).pack()

# text field
searchBoxClient = Tkinter.Text(searchBoxClientFrame, height=1, width=30).pack()

# function when button is pressed
def getOutput():
    outputFrame.pack_forget()
    outputFrame.pack()
    clientSearch = str(searchBoxClient.get(1.0, Tkinter.END))[:-1]
    # retrieve list of clients based on search query
    clientsFound = [s for s in df.groupby('clients').count().index.values if clientSearch.lower() in s.lower()]
    clientSelected = applicationui.Tkinter.StringVar(root)
    if len(clientsFound) > 0:
        clientSelected.set(clientsFound[0])
        Tkinter.OptionMenu(outputFrame, clientSelected, *clientsFound).pack()
    else:
        Tkinter.Label(outputFrame, text='Client not found!').pack()

Tkinter.Button(searchButtonFrame, text='Search', command=getOutput).pack()

root.mainloop()
Bas
  • 57
  • 1
  • 6

1 Answers1

0

We can actually update the value of the OptionMenu itself rather than destroying it (or it's parent) and then redrawing it. Credit to this answer for the below snippet:

import tkinter as tk

root = tk.Tk()
var = tk.StringVar(root)
choice = [1, 2, 3]
var.set(choice[0])

option = tk.OptionMenu(root, var, *choice)
option.pack()

def command():
    option['menu'].delete(0, 'end')
    for i in range(len(choice)):
        choice[i] += 1
        option['menu'].add_command(label=choice[i], command=tk._setit(var, choice[i]))
    var.set(choice[0])

button = tk.Button(root, text="Ok", command=command)
button.pack()

root.mainloop()
Ethan Field
  • 4,646
  • 3
  • 22
  • 43