0

I am trying to create a navigable tree of folders and subfolders using pystray. I am having trouble creating a recursive menu with pystray.

I am getting an error

"TypeError: MenuItem.__init__() takes from 3 to 8 positional arguments but 1757 were given".

Yes my folder has 1757 .cfr files...

The code is attached below. How can I create a recursive menu using pystray where only the last .cfr file of each folder is clickable while the other files in the folder are only for navigation?


import os

import pystray


class OpenTrees:
    def __init__(self, dir_path):
        self.dir_path = dir_path
        self.submenus = self._create_submenus()
        icon = pystray.Icon('name',
                            icon=pystray.Icon('icon.png', width=32, height=32))
        icon.menu = pystray.Menu(*self.submenus)
        icon.run()

    def _create_submenus(self, file_path=None):
        submenus = []
        file_path = file_path or self.dir_path
        for file in sorted(os.listdir(file_path)):
            full_file_path = os.path.join(file_path, file)

            if os.path.isdir(full_file_path):
                submenu = pystray.MenuItem(file, *self._create_submenus(
                    file_path=full_file_path))
                submenus.append(submenu)

            elif file.endswith('.cfr'):
                submenu = pystray.MenuItem(file, lambda: print('Hello'))
                submenus.append(submenu)

        return submenus


if __name__ == '__main__':
    OpenTrees(dir_path=r"D:\Trees\AllTrees")

Here is an visual example of what I would like as the final result, only the first .cfr item appears in the menu, and the folders are all navigable..

enter image description here

Collaxd
  • 425
  • 3
  • 12

1 Answers1

0
...
            if os.path.isdir(full_file_path):
                submenu = pystray.MenuItem(file, *self._create_submenus(
                    file_path=full_file_path))
                submenus.append(submenu)

2nd argument in pystray.MenuItem(file, *sequence, file_path=full_file_path) actually gets unpacked and becomes N arguments instead, you likely need to change that call into

pystray.MenuItem(file, self._create_submenus(
                    file_path=full_file_path))

note the missing *

https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists

ykhrustalev
  • 604
  • 10
  • 18
  • hello, your solution keep only the first level of folders in the menu [see](https://i.imgur.com/ZaazL4d.png) – Collaxd Feb 27 '23 at 13:06
  • try limiting a number of items passed by doing `self._create_submenus(file_path=full_file_path)[:5]` – ykhrustalev Feb 27 '23 at 13:20