将多个文件夹名称从目录添加到选项菜单Python

2024-03-29 07:46:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试向选项菜单添加多个文件夹名称。下面的代码只将一个文件夹名称添加到列表中,但我想添加目录中的所有文件夹名称。你知道吗

var = StringVar()
os.chdir('C:\\Users\\mhoban')
all_subdirs = [d for d in os.listdir('.') if os.path.isdir(d)]
for dirs in all_subdirs:
    dir = os.path.join('C:\\Users\\mhoban', dirs)
    os.chdir(dir)
    current = os.getcwd()
    new = str(current).split("\\")[3]

opt1 = OptionMenu(app, var, new)
opt1.grid(row=0, column=1, padx=10, pady=10)
opt1.configure(width = 40, bg = "White")

Tags: pathin文件夹名称forosvardir
1条回答
网友
1楼 · 发布于 2024-03-29 07:46:42

您需要构建一个菜单选项列表,然后在当前传递new的位置将其解压:

options = []
for dirs in all_subdirs:
    ...  # same
    options.append(str(current).split("\\")[3])

拆包options

opt1 = OptionMenu(app, var, *options)

注意:options将与all_subdirs相同,因此您的处理似乎没有取得任何效果。只需使用all_subdirs。你知道吗

相关问题 更多 >