pythonuser-interfacetkinter

Tkinter Combo Box, how to show all the folders in a parent folder and store it for later use


I can't seem to figure out how to make the Combo Box list all of the folders in the parent "soundpacks" folder. I need them to show, and being able to choose one is an integral part of the app I'm building.

import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
import os

root = tk.Tk()
root.resizable(width=False, height=False)
root.geometry("400x600")
root.title("VibesPlus")

logo = Image.open('img/download.png')
logo = ImageTk.PhotoImage(logo)

logo_label = tk.Label(root, image=logo)
logo_label.pack()

folder_path = "C:/Users/konel/Documents/Source/VibesPlus/soundpacks"
combo = ttk.Combobox(root, height=20, width=200, values=[folder_path])
combo.pack()

root.mainloop()

Here's what I have so far, and the combobox only shows the main folder's path.


Solution

  • Problem

    You wrote values=[folder_path]) which includes only the path, but a loop would be needed using the os.walk() method.

    Solution

    Instead you have to create a compressed loop, so that it takes the first element [0] of the files in a tree. The os.walk() method does just that, because it generates file names in a tree by walking up the tree down or down the tree.

    For understanding purposes, i write the uncompressed loop:

    for a in os.walk(folder_path):
        a[0]
    

    but actually compressed it should be [a[0] for a in os.walk(folder_path)]), so the solution is values=[a[0] for a in os.walk(folder_path)])

    Here is the solution for how to show all folders in one root folder and store it for later use

    import tkinter as tk
    from tkinter import ttk
    from PIL import Image, ImageTk
    import os
    
    root = tk.Tk()
    root.resizable(width=False, height=False)
    root.geometry("400x600")
    root.title("VibesPlus")
    
    logo = Image.open('img/download.png')
    logo = ImageTk.PhotoImage(logo)
    
    logo_label = tk.Label(root, image=logo)
    logo_label.pack()
    
    folder_path = "C:/Users/konel/Documents/Source/VibesPlus/soundpacks"
    combo = ttk.Combobox(root, height=20, width=200, values=[a[0] for a in os.walk(folder_path)])
    combo.pack()
    
    root.mainloop()