Search code examples
pythontkinteroptionmenu

Add many times a result form an optionmenu to a label


i am learning python and how to use tkinter. As exercise,i wanted to add, in the same label, many results from an option menu. as i did not find a solution to make it, i tried to create a new label with different position each time i select a new option in my menu. But it is not working, it's look like i start an infinite process.

Here is my try, but it is not exactly what i want.

from tkinter import *
root = Tk()
root.title("Fruit list")
root.geometry("800x700")
root.config(bg = "white")

#Dictionnary:
Fruit= {
       'Apple': 'yellow juicy',
       'Strawberry': 'red sweet',
       'Orange': 'orange juicy',
       'Tomato': 'red juicy',
}

def selected(event):
    n_num = 0
    r_num = 6
    c_num = 1

    varclicked = clicked.get()
    r_fruit = Label(root, text= varclicked)
    r_fruit.grid(row=r_num, column=c_num, padx=5, pady=5)
    r_fruit.config(bg="white")
    n_num +=1

    while n_num!=10:
        if 1<n_num<4 or 6<n_num<10:
            varclicked = clicked.get()
            r_fruit = Label(root, text=varclicked)
            r_fruit.grid(row=r_num, column=c_num, padx=5, pady=5)
            r_fruit.config(bg="white")
            n_num += 1
            c_num += 1
        elif n_num == 5:
            r_num += 1
            c_num = 1
            varclicked = clicked.get()
            r_fruit = Label(root, text=varclicked)
            r_fruit.grid(row=r_num, column=c_num, padx=5, pady=5)
            r_fruit.config(bg="white")
            n_num += 1

clicked = StringVar(root)
clicked.set('Choose a Fruit')
lst_fruit = OptionMenu(root, clicked, *Fruit, command=selected)
lst_fruit.grid(row=7, column=0)


root.mainloop()

Solution

  • First, to avoid the infinite loop, make sure n_num is always incremented. E.g.:

    if (1<=n_num<=4) or (6<=n_num<10):
    

    A more complete example, may help:

    from tkinter import *
    
    root = Tk()
    
    Fruit= {
           'Apple': 'yellow juicy',
           'Strawberry': 'red sweet',
           'Orange': 'orange juicy',
           'Tomato': 'red juicy',
    }
    
    l = Label(root, text='')
    l.pack()
    
    def selected(event):
      prevText = l.cget('text')
      sep = '\n' if prevText else ''
      addedText = clicked.get()
      l.config(text=f'{prevText}{sep}{addedText}')
    
    clicked = StringVar(root, 'Choose a Fruit')
    lst_fruit = OptionMenu(
      root, clicked, *Fruit, command=selected
    )
    lst_fruit.pack()
    
    root.mainloop()