Python 使用PyQt5 完成选择文件或目录的对话框方法

yipeiwu_com5年前Python基础

如下所示:

import sys
from PyQt5.QtWidgets import QMainWindow,QApplication,QTextEdit,QAction,QFileDialog
from PyQt5.QtGui import QIcon

class Example(QMainWindow):
  def __init__(self):
    super(Example, self).__init__()
    self.initUI()
  def initUI(self):
    self.textEdit = QTextEdit()
    self.setCentralWidget(self.textEdit)
    self.statusBar()

    openfile = QAction(QIcon(r'C:\Users\Administrator\PycharmProjects\QT\picture\文件.jpg'),'open',self)
    openfile.setShortcut("Ctrl + 0")
    openfile.setStatusTip('open new file')
    openfile.triggered.connect(self.showDialog)

    menubar = self.menuBar()
    filemune = menubar.addMenu('$File')
    filemune.addAction(openfile)

    self.setGeometry(300,300,300,300)
    self.setWindowTitle('FIEL dialog')
    self.show()
  def showDialog(self):
    fname = QFileDialog.getOpenFileName(self,'open file', '/')
    if fname[0]:
      try:
        f = open(fname[0], 'r')
        with f:
          data = f.read()
          self.textEdit.setText(data)
      except:
        self.textEdit.setText("打开文件失败,可能是文件内型错误")
if __name__ == "__main__":
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

以上这篇Python 使用PyQt5 完成选择文件或目录的对话框方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

简单理解Python中基于生成器的状态机

 简单生成器有许多优点。生成器除了能够用更自然的方法表达一类问题的流程之外,还极大地改善了许多效率不足之处。在 Python 中,函数调用代价不菲;除其它因素外,还要花一段时间...

python 以16进制打印输出的方法

打印整数16进制 num=10 print('%#x'%num) 打印字符串中的16进制 arr='12342535' for i in arr: print('%#x'%o...

python输入多行字符串的方法总结

Python中输入多行字符串: 方法一:使用三引号 >>> str1 = '''Le vent se lève, il faut tenter de vivre....

详解Python中列表和元祖的使用方法

详解Python中列表和元祖的使用方法

list Python内置的一种数据类型是列表:list。list是一种有序的集合,可以随时添加和删除其中的元素。 比如,列出班里所有同学的名字,就可以用一个list表示: >...

Python 实现12306登录功能实例代码

下面一段代码给大家带来了python实现12306登录功能,具体代码如下所示: #!/usr/bin/env python import requests import urllib...