List boxes doesn't load/appear

Hi there,

First post and totally newbie with Python.

With a lot of help from GPT-4 in Edge i’ve made this folder indexing-tool with a searchbar and checkboxes that should hide and show some listboxes
And this actually works perfectly.

With assistance from GPT-4 in Edge I “just” wanted to integrate it in a toggle window-function so the starting window would be minimize to a preset place on the screen, with a single button. by presssing that button the window should expand to “normal size” known form the fist code attempt.

I can make it work, but then the order of the widgets isn’t correct!
I’d like the Searchbar at the top followed by the checkboxes and then the Listboxes. But “the working attempt of code” loads the listboxes, the searchbar and then the checkboxes.
The idea was as by checking/unchecking the checkboxes; the height of the window gets longer/shorter and only shows the checked listboxes in the correct order.

I don’t know if anybody can figure out a solution in this pretty messy piece of code below!?

If the entire code, is needed I can load this as well.

def toggle_window(state):
    if state == "expand":
        screen_width = window.winfo_screenwidth()  
        window.geometry(f"300x700+{screen_width-300}+55")  
        window.overrideredirect(0)  
        window.resizable(True, True)  

        arrowleft_button.pack_forget()
        close_button.pack_forget()
        arrowright_button.place(relx=0.97, rely=0.005, anchor='ne')  




        ########################

        # Load the logo image (ensure the image file is in the same directory as your script)
        logo = tk.PhotoImage(file=logo_path)

        # Create a label with the logo image
        #logo_label = tk.Label(window, image=logo)
        logo_label = tk.Label(window, image=logo, borderwidth=0)
        logo_label.image = logo  # Keep a reference to prevent garbage collection

        # Position the label at the lower right corner of the window
        logo_label.place(relx=1, rely=1, anchor='se')


        ########################







        # Pack search entry first
        search_entry.pack(pady=7)  

        configure_checkboxes()

        # Then pack checkboxes
        chk_frame.pack()  

        # Forget all listboxes and labels
#####        for idx in indexes:
#####            lb, lbl, var = listboxes[idx]
#####            lbl.pack_forget()
#####            lb.pack_forget()

        # Pack listboxes and labels that are checked in the order of indexes
  #####      for idx in indexes:
  #####          lb, lbl, var = listboxes[idx]
  #####          if var.get():
  #####              lbl.pack(pady=(8,0))  # Add space above the label
  #####              lb.pack()  # Add space below the listbox

        # Update window size
        total_height = 150
        #lbl.pack_forget()
        #lb.pack_forget()
        search_entry.pack(pady=7)
        chk_frame.pack()
        #for index in indexes:
        for idx in indexes:
            #lb, lbl, var = listboxes[index]
            if var.get():
                #lbl.pack_forget()
                #lb.pack_forget()
#                search_entry.pack(pady=7)
#                chk_frame.pack()
                total_height += lb.winfo_reqheight() + lbl.winfo_reqheight() + 8
                lbl.pack(pady=(8,0))  # Add space above the label
                lb.pack()  # Add space below the listbox
                #lb, lbl, var = listboxes[index]
        window.geometry(f'300x{total_height}')  # Add total height to initial height
        lb, lbl, var = listboxes[index]

    elif state == "shrink":
        window.geometry("38x50-0+55")  
        window.overrideredirect(1)  
        arrowright_button.place_forget()
        search_entry.pack_forget()  
        chk_frame.pack_forget()  # Forget checkboxes here




        # Hide all listboxes and labels
        for index in indexes:
            lb, lbl, var = listboxes[index]
            lbl.pack_forget()
            lb.pack_forget()

        arrowleft_button.pack(pady=10)
        #close_button.pack()


        #logo_label.place_forget()

any help appreciated! :slight_smile:

PS. By the way… I’ve also created this post on DEV, but might take it down again, as this community/forum seems more python-related or the right spot for python stuff…?

Hello and welcome.

If you mean some unrelated forum named DEV, I’ve never heard of it.

If you mean the Core Development section of this forum, that’s for the people who are working to make future versions of Python itself - not for questions about using Python to make new programs.

Standard warnings here: GPT and other such AI chatbots (large language models, whatever you want to call them) literally do not know what they are talking about. They are very good at writing text that appears to be well-formed and convincing, and can emulate a lot of writing styles - but they do not, and cannot, verify the truth or rationality of that output. They are perfectly capable of giving code examples that are complete nonsense, making up library functions that don’t exist, etc. You can prompt them to defend themselves and they will (usually) output text that reads like a solid defense; but this does not mean they are conscious or intelligent, any more than a book titled “I Am Conscious and Intelligent” would be.

I’m assuming here that you don’t already have experience with other programming languages. The project you describe is reasonably small, and with time you can surely create much greater things. But as a beginner there are more fundamental concepts to learn first, and you should expect to need some time to study them. If you are just trying to get GPT-4 to output some code and get the code to work then you are not really practicing the craft of programming. If you try to get help from others with code, they will not realistically be able to tell you what to prompt GPT with in order to fix the problem; they can only treat the code as if you had written it yourself - and the less true that is, the greater the risk of confusion. Code that you had to write yourself is code that you’ve practiced understanding (along with the skills related to understanding code, such as analyzing error messages).

My other advice is to learn to use a version control system. This way, you can always go back to earlier attempts at the code, instead of trying to comment them all out and then uncomment the right part later. It’s much better organized and avoids lots of mistakes and confusion.

The code shown here doesn’t seem to be self-contained, at least when the commented-out parts are commented out. In particular, it seems as if you expect variables like lb and lbl to be remembered between calls to toggle_window. It’s possible to use “global” variables to make this happen, but without a global statement in the code, they cannot be reassigned inside the function. There are a few important details for this, so here are some reference links:

Hi again,

DEV = https://dev.to/ but as I said I didn’t think it was the right community.

I’m aware about the limitations in bots, but to let them come up with a suggestion in how some code in Python could be written, is quite neat and then you’ll have it right away. That means I don’t have to wait for days until a skilled volunteer like you self, has the time to analyze and probably “solve” my current problem.

I’ve done some nice macros in Excel, but not without help like by searching the entire net and keep on digging until a solution that fits my problem is found, but your definitely right; I am pretty green in Python, C, realbasic and so forth.

The reason why a lot of the lines is commented-out is the tests I’ve done in order to try to solve with the GPT feedback … which apparently didn’t work!
And now I took a new step … a step into a forum I think have the ability to solve the mystery I’m facing.

I appreciate your links that probably would be a gamechanger to me, but I’m really dumb to read and then understand such stuff…

I’d be happy to show the entire code, but I probably will change some of the paths for the actual indexing so it isn’t spread out on the entire internet.

/C

Asking for a little help.

Have this code:

import tkinter as tk
from tkinter import ttk
import tkinter.messagebox
import os
import sys
import shutil
from datetime import datetime

dir_path = os.path.dirname(os.path.abspath(sys.argv[0]))
logo_path = os.path.join(dir_path, 'logo.png')

INDEX1 = [
    r"H:\SE\00",
    r"H:\SE\10",
    r"H:\SE\20",
    r"H:\SE\30",
    r"H:\SE\40",
    r"H:\SE\50",
    r"H:\SE\60",
    r"H:\SE\70",
    r"H:\SE\80",
    r"H:\SE\90"
]

INDEX2 = [r"H:\DXF"]
INDEX3 = [r"H:\PDF"]
INDEX4 = [r"H:\cad"]
INDEX5 = [r"H:\STEP"] 
INDEX6 = [r"H:\PDF\10\11xxx El"] 
INDEX7 = [r"I:\Dok"]  

def open_file(event):
    selected_item = event.widget.get(event.widget.curselection())
    if selected_item:
        try:
            full_path = full_paths.get(selected_item, selected_item)
            step_open_dir = os.path.join(os.path.expanduser('~'), 'Documents', '_STEP_OPEN_')
            os.makedirs(step_open_dir, exist_ok=True)
            timestamp = datetime.now().strftime('%H%M%S')
            filename = os.path.basename(full_path)
            new_dir = os.path.join(step_open_dir, f'{filename}_{timestamp}')
            os.makedirs(new_dir, exist_ok=True)
            new_file_path = os.path.join(new_dir, filename)
            shutil.copy2(full_path, new_file_path)
            os.startfile(new_file_path)
        except Exception as e:
            tkinter.messagebox.showerror("Error", f"Failed to open file: {selected_item}\nError: {e}")            

extensions = {
    'INDEX1': ('.dft', '.par', '.psm', '.asm'),
    'INDEX2': ('.dxf',),
    'INDEX3': ('.pdf',),
    'INDEX4': ('.dwg',),
    'INDEX5': ('.stp',),
    'INDEX6': ('.pdf',),
    'INDEX7': ('.jpg', '.doc', '.docx', '.xls', '.xlsx', '.pdf', '.rar', '.zip', '.tif', '.bmp', '.htm')
}

indexes = ['INDEX1', 'INDEX2', 'INDEX3', 'INDEX4', 'INDEX5', 'INDEX6', 'INDEX7']
listboxes = {}
checkboxes = {}
full_paths = {}

def perform_search(event=None):
    global full_paths  
    full_paths = {}  
    search_value = search_entry.get()
    search_results = {}

    for index in indexes:
        lb, lbl, var = listboxes[index]
        if var.get():  
            results = []
            for folder in globals()[index]:
                for root, dirs, files in os.walk(folder):
                    if index == 'INDEX7':  
                        for dir in dirs:
                            if search_value.lower() in dir.lower():
                                results.append(os.path.join(root, dir))
                    for file in files:
                        if file.endswith(extensions[index]):  
                            results.append(os.path.join(root, file))
            search_results[index] = results

    for index, results in search_results.items():
        lb, lbl, var = listboxes[index]
        lb.delete(0, tk.END)
        if results:
            for result in results:
                if index == 'INDEX5':  
                    filename = os.path.basename(result)
                    lb.insert(tk.END, filename)
                    full_paths[filename] = result  
                else:
                    lb.insert(tk.END, result)
        else:
            lb.insert(tk.END, "Ingenting fundet")

arrowleft_path = os.path.join(dir_path, 'arrowleft.png')
arrowright_path = os.path.join(dir_path, 'arrowright.png')

window = tk.Tk()
window.title("FindThatFreakingFile - v4")
window.configure(bg="#245096")
window.attributes("-topmost", True)
window.overrideredirect(1)  

arrowleft = tk.PhotoImage(file=arrowleft_path)
arrowright = tk.PhotoImage(file=arrowright_path)

arrowleft_button = tk.Button(window, image=arrowleft, command=lambda: toggle_window("expand"))
arrowleft_button.image = arrowleft  

arrowright_button = tk.Button(window, image=arrowright, command=lambda: toggle_window("shrink"))
arrowright_button.image = arrowright  

close_button = tk.Button(window, text="X", command=window.destroy, width=1, height=1, font=("Arial", 10))

search_entry = ttk.Entry(window, font=("Arial", 12))
search_entry.bind("<Return>", perform_search)

chk_frame = ttk.Frame(window)
chk_frame.pack()

index_names = {
    'INDEX1': 'Solid',
    'INDEX2': 'DXF',
    'INDEX3': 'PDF',
    'INDEX4': 'CAD',
    'INDEX5': 'STEP',
    'INDEX6': 'El',
    'INDEX7': 'I:\Dok'
}

# Create a frame for listboxes
lb_frame = tk.Frame(window, bg="#245096")  
lb_frame.pack()


def configure_checkboxes():
    for index in indexes:
        checkboxes[index].config(command=lambda index=index: checkbox_command(index))




def create_listboxes():
    for i, index in enumerate(indexes, start=1):
        var = tk.BooleanVar(value=True if i <= 4 else False)
        chk = ttk.Checkbutton(chk_frame, text=index_names[index], variable=var)
        row = (i-1) // 2
        column = (i-1) % 2
        chk.grid(row=row, column=column, sticky='w')
        checkboxes[index] = chk

        if i == len(indexes):  
            chk.grid(row=row, column=0, columnspan=2, sticky='w')
        else:
            chk.grid(row=row, column=column, sticky='w')

        if index == 'INDEX7':  
            lb = tk.Listbox(lb_frame, width=200, height=10, bg="white", font=("Arial", 10))
        else:  
            lb = tk.Listbox(lb_frame, width=200, height=4, bg="white", font=("Arial", 10))

        lbl = ttk.Label(lb_frame, text=index_names[index])
        listboxes[index] = (lb, lbl, var)  
        lb.bind("<Double-Button-1>", open_file)


def checkbox_command(index):
    # Forget all listboxes and labels
    for idx in indexes:
        lb, lbl, var = listboxes[idx]
        lbl.pack_forget()
        lb.pack_forget()

    # Pack listboxes and labels that are checked in the order of indexes
    for idx in indexes:
        lb, lbl, var = listboxes[idx]
        if var.get():
            lbl.pack(pady=(8,0))  # Add space above the label
            lb.pack()  # Add space below the listbox

    # Update window size
    total_height = 150 
    for index in indexes:
        lb, lbl, var = listboxes[index]
        if var.get():
            lbl.pack_forget()
            lb.pack_forget()
            search_entry.pack(pady=7)
            chk_frame.pack()
            total_height += lb.winfo_reqheight() + lbl.winfo_reqheight() + 8
    window.geometry(f'300x{total_height}')  # Add total height to initial height






create_listboxes()  # Move this line to the beginning of the code


def toggle_window(state):
    if state == "expand":
        screen_width = window.winfo_screenwidth()  
        window.geometry(f"300x700+{screen_width-300}+55")  
        window.overrideredirect(0)  
        window.resizable(True, True)  

        arrowleft_button.pack_forget()
        close_button.pack_forget()
        arrowright_button.place(relx=0.97, rely=0.005, anchor='ne')  

        
        
        
        ########################
        
        # Load the logo image (ensure the image file is in the same directory as your script)
        logo = tk.PhotoImage(file=logo_path)

        # Create a label with the logo image
        #logo_label = tk.Label(window, image=logo)
        logo_label = tk.Label(window, image=logo, borderwidth=0)
        logo_label.image = logo  # Keep a reference to prevent garbage collection

        # Position the label at the lower right corner of the window
        logo_label.place(relx=1, rely=1, anchor='se')


        ########################







        # Pack search entry first
        search_entry.pack(pady=7)  

        configure_checkboxes()

        # Then pack checkboxes
        chk_frame.pack()  

        # Update window size
        total_height = 150
        #lbl.pack_forget()
        #lb.pack_forget()
        search_entry.pack(pady=7)
        chk_frame.pack()
        #for index in indexes:
        for idx in indexes:
            #lb, lbl, var = listboxes[index]
            if var.get():
                #lbl.pack_forget()
                #lb.pack_forget()
#                search_entry.pack(pady=7)
#                chk_frame.pack()
                total_height += lb.winfo_reqheight() + lbl.winfo_reqheight() + 8
                lbl.pack(pady=(8,0))  # Add space above the label
                lb.pack()  # Add space below the listbox
                #lb, lbl, var = listboxes[index]
        window.geometry(f'300x{total_height}')  # Add total height to initial height
        lb, lbl, var = listboxes[index]

    elif state == "shrink":
        window.geometry("38x50-0+55")  
        window.overrideredirect(1)  
        arrowright_button.place_forget()
        search_entry.pack_forget()  
        chk_frame.pack_forget()  # Forget checkboxes here


        
        
        # Hide all listboxes and labels
        for index in indexes:
            lb, lbl, var = listboxes[index]
            lbl.pack_forget()
            lb.pack_forget()

        arrowleft_button.pack(pady=10)
        #close_button.pack()
        

        #logo_label.place_forget()


# Set command for checkboxes
#for index in indexes:
#    checkboxes[index].config(command=lambda index=index: checkbox_command(index))

perform_search()

arrowleft_button.pack(pady=10)
#close_button.pack()
search_entry.pack_forget()
chk_frame.pack_forget()
for index in indexes:
    lb, lbl, var = listboxes[index]
    #lbl.pack_forget()
    #lb.pack_forget()

window.geometry("38x50-0+55")  
window.mainloop()

I have the following issues:

First issue:
I would like the Listboxes to load or be visible in the expand window.
…but only the checked listboxes. the window is ment to expand in ordre of the checked amount of listboxes.
The ordre of the widgets in the window should be like this:
searchbar
checkboxes
listboxes

Second issue:
The Logo.png is loaded when I go from expand to shrink window, but it shouldn’t.

Third issue:
The search function doesen’t seem to work (or I don’t think it works, but i cant test it as the listboxes isn’t visible)

any help is appreciated!
thank you.

/C

I guess I shouldn’t expect any kind of help … is that how I should see it?

I’ve provided a code I have some problems with …but what am I missing?

Hi Karl,

Any ideas why nobody wants to help me with my problem?