Pyqt清空Win回收站

     Pyqt清空回收站其實的調用Python的第三方庫,經過第三方庫調用windows的api刪除回收站的數據html

一. 準備工做

先下載第三方庫winshellpython

下載地址: https://github.com/tjguk/winshell/tree/stablegit

關於winshell的文檔: http://winshell.readthedocs.org/en/latest/recycle-bin.html#winshell.ShellRecycleBin.versionsgithub

該庫依賴於win32con (自行下載安裝)shell

安裝winshellwindows

1 python setup.py install

使用的時候  import winshellapi

 

二. 建立UI

用Py Designer 設計出UI,本部分主要用到pyqt的 QTableWidgetapp

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <ui version="4.0">
 3  <class>recycleBin</class>
 4  <widget class="QWidget" name="recycleBin">
 5   <property name="geometry">
 6    <rect>
 7     <x>0</x>
 8     <y>0</y>
 9     <width>640</width>
10     <height>422</height>
11    </rect>
12   </property>
13   <property name="windowTitle">
14    <string>Form</string>
15   </property>
16   <widget class="QGroupBox" name="groupBox">
17    <property name="geometry">
18     <rect>
19      <x>30</x>
20      <y>20</y>
21      <width>561</width>
22      <height>311</height>
23     </rect>
24    </property>
25    <property name="title">
26     <string>回收站列表</string>
27    </property>
28    <widget class="QTableWidget" name="tableWidget">
29     <property name="geometry">
30      <rect>
31       <x>10</x>
32       <y>20</y>
33       <width>541</width>
34       <height>271</height>
35      </rect>
36     </property>
37     <column>
38      <property name="text">
39       <string>名稱</string>
40      </property>
41      <property name="font">
42       <font>
43        <pointsize>12</pointsize>
44        <weight>50</weight>
45        <bold>false</bold>
46       </font>
47      </property>
48     </column>
49     <column>
50      <property name="text">
51       <string>路徑</string>
52      </property>
53      <property name="font">
54       <font>
55        <pointsize>12</pointsize>
56       </font>
57      </property>
58     </column>
59    </widget>
60   </widget>
61   <widget class="QPushButton" name="pushButtonok">
62    <property name="geometry">
63     <rect>
64      <x>470</x>
65      <y>360</y>
66      <width>75</width>
67      <height>23</height>
68     </rect>
69    </property>
70    <property name="text">
71     <string>清空</string>
72    </property>
73   </widget>
74  </widget>
75  <resources/>
76  <connections/>
77 </ui>

預覽: ide

而後 將Ui轉換爲py文件ui

 

三. 邏輯的實現

選引入winshell

 

1 import winshell

獲取 回收站裏面的對象

1 All_files = winshell.recycle_bin()
winshell. recycle_bin ( )

Returns a ShellRecycleBin object representing the system Recycle Bin

winshell. undelete ( filepath )

Find the most recent version of filepath to have been recycled and restore it to its original location on the filesystem. If a file already exists at that filepath, the copy will be renamed. The resulting filepath is returned.

class winshell. ShellRecycleBin

An object which represents the union of all the recycle bins on this system. The Shell subsystem doesn’t offer any way to access drive-specific bins (except by coming across them 「accidentally」 as shell folders within their specific drives).

The object (which is returned from a call to recycle_bin()) is iterable, returning the deleted items wrapped in ShellRecycledItem objects. It also exposes a couple of common-need convenience methods: versions() returns a list of all recycled versions of a given original filepath; andundelete() which restores the most-recently binned version of a given original filepath.

The object has the following methods:

empty ( confirm=Trueshow_progress=Truesound=True )

Empty all system recycle bins, optionally prompting for confirmation, showing progress, and playing a sort of crunching sound.

undelete ( filepath )

cf undelete() which is a convenience wrapper around this method.

versions ( filepath )

Return a (possibly empty) list of all recycled versions of a given filepath. Each item in the list is a ShellRecycledItem.

獲取對象的名稱和路徑
 1 self.dicFile = {}
 2         if All_files:
 3             for fileitem in All_files:
 4                 Fpath = str(fileitem.name())  # 獲取文件的路徑
 5                 FsplitName = Fpath.split('\\')
 6                 Fname=FsplitName[-1]  # 獲取文件的名稱
 7                 self.dicFile[Fname] = Fpath
 8         else:
 9             # self.initUi.tableWidget.hide()  # 回收站沒有東西,隱藏tableWidget    不一樣電腦系統有的不執行該方法
10             self.emptytable()

將獲取的數據保存在dicFile中,循環dicFile輸出在 tableWidget 

 1 if self.dicFile:
 2             Rowcount = len(self.dicFile)  # 求出回收站項目的個數
 3             self.initUi.tableWidget.setColumnCount(2)  # 列數固定爲2
 4             self.initUi.tableWidget.setRowCount(Rowcount)  # 行數爲項目的個數
 5             self.initUi.tableWidget.setColumnWidth(1,400)  # 設置第2列寬度爲400像素
 6             i = 0
 7             for datakey,datavalue in self.dicFile.items():
 8                 newItem = QtGui.QTableWidgetItem(unicode(datakey))
 9                 newItemPath = QtGui.QTableWidgetItem(unicode(datavalue))
10                 self.initUi.tableWidget.setItem(i, 0, newItem)
11                 self.initUi.tableWidget.setItem(i, 1, newItemPath)
12                 i += 1
13  else:
14        self.emptytable()

判斷回收站是否有數據對象

 1         self.initUi.tableWidget.setColumnCount(2)
 2         self.initUi.tableWidget.setRowCount(8)
 3         self.initUi.tableWidget.setColumnWidth(1,400)
 4         self.initUi.tableWidget.verticalHeader().setVisible(False)
 5         self.initUi.tableWidget.horizontalHeader().setVisible(False)
 6         textfont = QtGui.QFont("song",  17, QtGui.QFont.Bold)
 7         empinfo=QtGui.QTableWidgetItem(u'回收站內容爲空,無需清理!')
 8         empinfo.setFont(textfont)
 9         self.initUi.tableWidget.setItem(0, 0, empinfo)
10         self.initUi.tableWidget.setSpan(0, 0, 8, 2)
11         self.initUi.pushButtonok.hide()

 

完整代碼:

  1 # -*- coding: utf-8 -*-
  2 
  3 # Form implementation generated from reading ui file 'recycle.ui'
  4 #
  5 # Created: Thu Jan 15 19:14:32 2015
  6 #      by: PyQt4 UI code generator 4.10.3
  7 #
  8 # WARNING! All changes made in this file will be lost!
  9 
 10 from PyQt4 import QtCore, QtGui
 11 
 12 try:
 13     _fromUtf8 = QtCore.QString.fromUtf8
 14 except AttributeError:
 15     def _fromUtf8(s):
 16         return s
 17 
 18 try:
 19     _encoding = QtGui.QApplication.UnicodeUTF8
 20     def _translate(context, text, disambig):
 21         return QtGui.QApplication.translate(context, text, disambig, _encoding)
 22 except AttributeError:
 23     def _translate(context, text, disambig):
 24         return QtGui.QApplication.translate(context, text, disambig)
 25 
 26 class Ui_recycleBin(object):
 27     def setupUi(self, recycleBin):
 28         recycleBin.setObjectName(_fromUtf8("recycleBin"))
 29         recycleBin.resize(640, 422)
 30         self.groupBox = QtGui.QGroupBox(recycleBin)
 31         self.groupBox.setGeometry(QtCore.QRect(30, 20, 561, 311))
 32         self.groupBox.setObjectName(_fromUtf8("groupBox"))
 33         self.tableWidget = QtGui.QTableWidget(self.groupBox)
 34         self.tableWidget.setGeometry(QtCore.QRect(10, 20, 541, 271))
 35         self.tableWidget.setObjectName(_fromUtf8("tableWidget"))
 36         self.tableWidget.setColumnCount(2)
 37         self.tableWidget.setRowCount(0)
 38         item = QtGui.QTableWidgetItem()
 39         font = QtGui.QFont()
 40         font.setPointSize(12)
 41         font.setBold(False)
 42         font.setWeight(50)
 43         item.setFont(font)
 44         self.tableWidget.setHorizontalHeaderItem(0, item)
 45         item = QtGui.QTableWidgetItem()
 46         font = QtGui.QFont()
 47         font.setPointSize(12)
 48         item.setFont(font)
 49         self.tableWidget.setHorizontalHeaderItem(1, item)
 50         self.pushButtonok = QtGui.QPushButton(recycleBin)
 51         self.pushButtonok.setGeometry(QtCore.QRect(470, 360, 75, 23))
 52         self.pushButtonok.setObjectName(_fromUtf8("pushButtonok"))
 53 
 54         self.retranslateUi(recycleBin)
 55         QtCore.QMetaObject.connectSlotsByName(recycleBin)
 56 
 57     def retranslateUi(self, recycleBin):
 58         recycleBin.setWindowTitle(_translate("recycleBin", "Form", None))
 59         self.groupBox.setTitle(_translate("recycleBin", "回收站列表", None))
 60         item = self.tableWidget.horizontalHeaderItem(0)
 61         item.setText(_translate("recycleBin", "名稱", None))
 62         item = self.tableWidget.horizontalHeaderItem(1)
 63         item.setText(_translate("recycleBin", "路徑", None))
 64         self.pushButtonok.setText(_translate("recycleBin", "清空", None))
 65 
 66 
 67 
 68 
 69 import winshell
 70 #邏輯class
 71 class Logicpy(QtGui.QWidget):
 72     def __init__(self):
 73         super(Logicpy, self).__init__()
 74         self.initUi = Ui_recycleBin()
 75         self.initUi.setupUi(self)
 76         self.setWindowTitle(u'清空回收站')
 77         self.initUi.tableWidget.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)    # 將表格變爲禁止編輯
 78         self.initUi.tableWidget.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)  # 整行選中的方式
 79         self.initUi.tableWidget.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)  #設置爲能夠選中多個目標
 80         # self.connect(self.initUi.pushButtonok, QtCore.SIGNAL('clicked()'), self.btnempty('sdf'))
 81         self.initUi.pushButtonok.mouseReleaseEvent=self.btnempty
 82         reload(sys)
 83         sys.setdefaultencoding("utf-8")
 84         All_files = winshell.recycle_bin()
 85         self.dicFile = {}
 86         if All_files:
 87             for fileitem in All_files:
 88                 Fpath = str(fileitem.name())  # 獲取文件的路徑
 89                 FsplitName = Fpath.split('\\')
 90                 Fname=FsplitName[-1]  # 獲取文件的名稱
 91                 self.dicFile[Fname] = Fpath
 92         else:
 93             # self.initUi.tableWidget.hide()  # 回收站沒有東西,隱藏tableWidget    不一樣電腦系統有的不執行該方法
 94             self.emptytable()
 95 
 96         self.interData()
 97     # 插入recycleBin 對象
 98     def interData(self):
 99         if self.dicFile:
100             Rowcount = len(self.dicFile)  # 求出回收站項目的個數
101             self.initUi.tableWidget.setColumnCount(2)  # 列數固定爲2
102             self.initUi.tableWidget.setRowCount(Rowcount)  # 行數爲項目的個數
103             self.initUi.tableWidget.setColumnWidth(1,400)  # 設置第2列寬度爲400像素
104             i = 0
105             for datakey,datavalue in self.dicFile.items():
106                 newItem = QtGui.QTableWidgetItem(unicode(datakey))
107                 newItemPath = QtGui.QTableWidgetItem(unicode(datavalue))
108                 self.initUi.tableWidget.setItem(i, 0, newItem)
109                 self.initUi.tableWidget.setItem(i, 1, newItemPath)
110                 i += 1
111         else:
112             self.emptytable()
113     # 運行程序時, 回收站爲空
114     def emptytable(self):
115         self.initUi.tableWidget.setColumnCount(2)
116         self.initUi.tableWidget.setRowCount(8)
117         self.initUi.tableWidget.setColumnWidth(1,400)
118         self.initUi.tableWidget.verticalHeader().setVisible(False)
119         self.initUi.tableWidget.horizontalHeader().setVisible(False)
120         textfont = QtGui.QFont("song",  17, QtGui.QFont.Bold)
121         empinfo=QtGui.QTableWidgetItem(u'回收站內容爲空,無需清理!')
122         empinfo.setFont(textfont)
123         self.initUi.tableWidget.setItem(0, 0, empinfo)
124         self.initUi.tableWidget.setSpan(0, 0, 8, 2)
125         self.initUi.pushButtonok.hide()
126     # 觸發btn時清空回收站
127     def btnempty(self,event):
128         ev=event.button()
129         OK = winshell.ShellRecycleBin.empty() # 如何判斷返回類型?
130         self.close()
131 
132 
133 
134 
135 
136     #重載keyPressEvent ,  當按下Esc退出
137     def keyPressEvent(self, event):
138         if event.key() ==QtCore.Qt.Key_Escape:
139             self.close()
140 
141 
142 
143 
144 if __name__ == "__main__":
145     import sys
146     app = QtGui.QApplication(sys.argv)
147     RecycleLogic = Logicpy()
148     RecycleLogic.show()
149     sys.exit(app.exec_())

五. 運行效果

相關文章
相關標籤/搜索