文件夹层次结构中文件的构建菜单

2024-04-24 08:13:10 发布

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

我有一个文件夹,在那个文件夹里是文件和其他文件夹,里面有文件和文件夹等等。现在我要做的是做一个下拉菜单,把每个文件名添加到菜单中,如果是文件夹,它会创建一个子菜单并将该文件夹中的文件名添加到菜单中,等等。我有一些(不完整的)代码:

def TemplatesSetup(self):

  # add templates menu
  template_menu = self.menubar.addMenu('&Templates')

  #temp = template_menu.addMenu()

  # check if templates folder exists
  if os.path.exists('templates/') is False:
    temp = QAction('Can not find templates folder...', self)
    temp.setDisabled (1)
    template_menu.addAction(temp)
    return

  for fulldir, folder, filename in os.walk('templates'):

    for f in filename:
      template_menu.addAction(QAction(f, self))

但我仍然不确定如何才能做到最好。有什么想法吗?在


Tags: 文件self文件夹ifos文件名exists菜单
1条回答
网友
1楼 · 发布于 2024-04-24 08:13:10

我为你树立了一个完整的榜样。在

import sys
import os
import os.path

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        template_menu = self.menuBar().addMenu('&Templates')
        menus = {'templates': template_menu}

        for dirpath, dirnames, filenames in os.walk('templates'):
            current = menus[dirpath]
            for dn in dirnames:
                menus[os.path.join(dirpath, dn)] = current.addMenu(dn)
            for fn in filenames:
                current.addAction(fn)

if __name__=='__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

相关问题 更多 >