Pyqt清空Win回收站

时间:2023-12-12 10:29:44

Pyqt清空回收站其实的调用Python的第三方库,通过第三方库调用windows的api删除回收站的数据

一. 准备工作

先下载第三方库winshell

下载地址: https://github.com/tjguk/winshell/tree/stable

关于winshell的文档: http://winshell.readthedocs.org/en/latest/recycle-bin.html#winshell.ShellRecycleBin.versions

该库依赖于win32con (自行下载安装)

安装winshell

 python setup.py install

使用的时候  import winshell

二. 创建UI

用Py Designer 设计出UI,本部分主要用到pyqt的 QTableWidget

 <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>recycleBin</class>
<widget class="QWidget" name="recycleBin">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>640</width>
<height>422</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<widget class="QGroupBox" name="groupBox">
<property name="geometry">
<rect>
<x>30</x>
<y>20</y>
<width>561</width>
<height>311</height>
</rect>
</property>
<property name="title">
<string>回收站列表</string>
</property>
<widget class="QTableWidget" name="tableWidget">
<property name="geometry">
<rect>
<x>10</x>
<y>20</y>
<width>541</width>
<height>271</height>
</rect>
</property>
<column>
<property name="text">
<string>名称</string>
</property>
<property name="font">
<font>
<pointsize>12</pointsize>
<weight>50</weight>
<bold>false</bold>
</font>
</property>
</column>
<column>
<property name="text">
<string>路径</string>
</property>
<property name="font">
<font>
<pointsize>12</pointsize>
</font>
</property>
</column>
</widget>
</widget>
<widget class="QPushButton" name="pushButtonok">
<property name="geometry">
<rect>
<x>470</x>
<y>360</y>
<width>75</width>
<height>23</height>
</rect>
</property>
<property name="text">
<string>清空</string>
</property>
</widget>
</widget>
<resources/>
<connections/>
</ui>

预览:

Pyqt清空Win回收站

然后 将Ui转换为py文件

三. 逻辑的实现

选引入winshell

 import winshell

获取 回收站里面的对象

 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.

classwinshell.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.

获取对象的名称和路径
 self.dicFile = {}
if All_files:
for fileitem in All_files:
Fpath = str(fileitem.name()) # 获取文件的路径
FsplitName = Fpath.split('\\')
Fname=FsplitName[-1] # 获取文件的名称
self.dicFile[Fname] = Fpath
else:
# self.initUi.tableWidget.hide() # 回收站没有东西,隐藏tableWidget 不同电脑系统有的不执行该方法
self.emptytable()

将获取的数据保存在dicFile中,循环dicFile输出在 tableWidget 

 if self.dicFile:
Rowcount = len(self.dicFile) # 求出回收站项目的个数
self.initUi.tableWidget.setColumnCount(2) # 列数固定为2
self.initUi.tableWidget.setRowCount(Rowcount) # 行数为项目的个数
self.initUi.tableWidget.setColumnWidth(1,400) # 设置第2列宽度为400像素
i = 0
for datakey,datavalue in self.dicFile.items():
newItem = QtGui.QTableWidgetItem(unicode(datakey))
newItemPath = QtGui.QTableWidgetItem(unicode(datavalue))
self.initUi.tableWidget.setItem(i, 0, newItem)
self.initUi.tableWidget.setItem(i, 1, newItemPath)
i += 1
else:
self.emptytable()

判断回收站是否有数据对象

         self.initUi.tableWidget.setColumnCount(2)
self.initUi.tableWidget.setRowCount(8)
self.initUi.tableWidget.setColumnWidth(1,400)
self.initUi.tableWidget.verticalHeader().setVisible(False)
self.initUi.tableWidget.horizontalHeader().setVisible(False)
textfont = QtGui.QFont("song", 17, QtGui.QFont.Bold)
empinfo=QtGui.QTableWidgetItem(u'回收站内容为空,无需清理!')
empinfo.setFont(textfont)
self.initUi.tableWidget.setItem(0, 0, empinfo)
self.initUi.tableWidget.setSpan(0, 0, 8, 2)
self.initUi.pushButtonok.hide()

完整代码:

 # -*- coding: utf-8 -*-

 # Form implementation generated from reading ui file 'recycle.ui'
#
# Created: Thu Jan 15 19:14:32 2015
# by: PyQt4 UI code generator 4.10.3
#
# WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig) class Ui_recycleBin(object):
def setupUi(self, recycleBin):
recycleBin.setObjectName(_fromUtf8("recycleBin"))
recycleBin.resize(640, 422)
self.groupBox = QtGui.QGroupBox(recycleBin)
self.groupBox.setGeometry(QtCore.QRect(30, 20, 561, 311))
self.groupBox.setObjectName(_fromUtf8("groupBox"))
self.tableWidget = QtGui.QTableWidget(self.groupBox)
self.tableWidget.setGeometry(QtCore.QRect(10, 20, 541, 271))
self.tableWidget.setObjectName(_fromUtf8("tableWidget"))
self.tableWidget.setColumnCount(2)
self.tableWidget.setRowCount(0)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(False)
font.setWeight(50)
item.setFont(font)
self.tableWidget.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setPointSize(12)
item.setFont(font)
self.tableWidget.setHorizontalHeaderItem(1, item)
self.pushButtonok = QtGui.QPushButton(recycleBin)
self.pushButtonok.setGeometry(QtCore.QRect(470, 360, 75, 23))
self.pushButtonok.setObjectName(_fromUtf8("pushButtonok")) self.retranslateUi(recycleBin)
QtCore.QMetaObject.connectSlotsByName(recycleBin) def retranslateUi(self, recycleBin):
recycleBin.setWindowTitle(_translate("recycleBin", "Form", None))
self.groupBox.setTitle(_translate("recycleBin", "回收站列表", None))
item = self.tableWidget.horizontalHeaderItem(0)
item.setText(_translate("recycleBin", "名称", None))
item = self.tableWidget.horizontalHeaderItem(1)
item.setText(_translate("recycleBin", "路径", None))
self.pushButtonok.setText(_translate("recycleBin", "清空", None)) import winshell
#逻辑class
class Logicpy(QtGui.QWidget):
def __init__(self):
super(Logicpy, self).__init__()
self.initUi = Ui_recycleBin()
self.initUi.setupUi(self)
self.setWindowTitle(u'清空回收站')
self.initUi.tableWidget.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) # 将表格变为禁止编辑
self.initUi.tableWidget.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows) # 整行选中的方式
self.initUi.tableWidget.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection) #设置为可以选中多个目标
# self.connect(self.initUi.pushButtonok, QtCore.SIGNAL('clicked()'), self.btnempty('sdf'))
self.initUi.pushButtonok.mouseReleaseEvent=self.btnempty
reload(sys)
sys.setdefaultencoding("utf-8")
All_files = winshell.recycle_bin()
self.dicFile = {}
if All_files:
for fileitem in All_files:
Fpath = str(fileitem.name()) # 获取文件的路径
FsplitName = Fpath.split('\\')
Fname=FsplitName[-1] # 获取文件的名称
self.dicFile[Fname] = Fpath
else:
# self.initUi.tableWidget.hide() # 回收站没有东西,隐藏tableWidget 不同电脑系统有的不执行该方法
self.emptytable() self.interData()
# 插入recycleBin 对象
def interData(self):
if self.dicFile:
Rowcount = len(self.dicFile) # 求出回收站项目的个数
self.initUi.tableWidget.setColumnCount(2) # 列数固定为2
self.initUi.tableWidget.setRowCount(Rowcount) # 行数为项目的个数
self.initUi.tableWidget.setColumnWidth(1,400) # 设置第2列宽度为400像素
i = 0
for datakey,datavalue in self.dicFile.items():
newItem = QtGui.QTableWidgetItem(unicode(datakey))
newItemPath = QtGui.QTableWidgetItem(unicode(datavalue))
self.initUi.tableWidget.setItem(i, 0, newItem)
self.initUi.tableWidget.setItem(i, 1, newItemPath)
i += 1
else:
self.emptytable()
# 运行程序时, 回收站为空
def emptytable(self):
self.initUi.tableWidget.setColumnCount(2)
self.initUi.tableWidget.setRowCount(8)
self.initUi.tableWidget.setColumnWidth(1,400)
self.initUi.tableWidget.verticalHeader().setVisible(False)
self.initUi.tableWidget.horizontalHeader().setVisible(False)
textfont = QtGui.QFont("song", 17, QtGui.QFont.Bold)
empinfo=QtGui.QTableWidgetItem(u'回收站内容为空,无需清理!')
empinfo.setFont(textfont)
self.initUi.tableWidget.setItem(0, 0, empinfo)
self.initUi.tableWidget.setSpan(0, 0, 8, 2)
self.initUi.pushButtonok.hide()
# 触发btn时清空回收站
def btnempty(self,event):
ev=event.button()
OK = winshell.ShellRecycleBin.empty() # 如何判断返回类型?
self.close() #重载keyPressEvent , 当按下Esc退出
def keyPressEvent(self, event):
if event.key() ==QtCore.Qt.Key_Escape:
self.close() if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
RecycleLogic = Logicpy()
RecycleLogic.show()
sys.exit(app.exec_())

五. 运行效果

Pyqt清空Win回收站Pyqt清空Win回收站Pyqt清空Win回收站Pyqt清空Win回收站Pyqt清空Win回收站