python - 在文件夹层次结构中构建文件菜单

标签 python user-interface pyqt

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

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))

但我仍然不确定最好的方法是什么。有什么想法吗?

最佳答案

我为你做了一个完整的例子。

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_())

关于python - 在文件夹层次结构中构建文件菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18198064/

相关文章:

python - Python将对象转换为 float

python更改UDPServer中的最大限制接收缓冲区

python - 如何在 Windows 上安装 scipy 包?

java - 设置 swing JSlider 和 JTextField 的勾选行为

python - QWizard:更改标题字段的高度/尺寸

python - 如何使用 Opencv 捕获帧

python - pylint 重复代码误报

c - 如何从头开始构建 GUI 工具包

javascript - HTML/JavaScript UI 小部件 GUI 生成器

python - PyQt - 从 URL 设置 QLabel 图像