Skip to content

Instantly share code, notes, and snippets.

@reee
Created November 3, 2023 00:24
Show Gist options
  • Save reee/84a17c525a72fc9b50d8df5b41febf70 to your computer and use it in GitHub Desktop.
Save reee/84a17c525a72fc9b50d8df5b41febf70 to your computer and use it in GitHub Desktop.
import os
import random
import configparser
import pickle
from PyQt6.QtWidgets import QApplication, QWidget, QPushButton, QLabel, QHBoxLayout, QVBoxLayout, QMessageBox, QListWidget, QListWidgetItem
import subprocess
FILEBROWSER_PATH = os.path.join(os.getenv('WINDIR'), 'explorer.exe')
import functools
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('RandPlay')
self.resize(280, 290)
self.initUI()
def initUI(self):
# 创建组件
self.cacheLabel = QLabel('缓存未建立')
self.cacheLabel.setStyleSheet('color: red')
self.buildCacheBtn = QPushButton('建立/重建 缓存')
self.randomOpenBtn = QPushButton('随机打开')
self.openedFileList = QListWidget()
# 设置布局
hbox = QHBoxLayout()
hbox.addWidget(self.cacheLabel)
hbox.addWidget(self.buildCacheBtn)
vbox = QVBoxLayout()
vbox.addLayout(hbox)
vbox.addWidget(self.randomOpenBtn)
vbox.addWidget(self.openedFileList)
self.setLayout(vbox)
# 连接信号和槽函数
self.buildCacheBtn.clicked.connect(self.buildCache)
self.randomOpenBtn.clicked.connect(self.randomOpen)
# 初始化
self.cacheExists = os.path.exists('db-file')
if self.cacheExists:
self.cacheLabel.setText('缓存已建立')
self.cacheLabel.setStyleSheet('color: green')
self.openedFiles = []
def buildCache(self):
# 遍历config.txt指定目录,将完整路径存入db-file
try:
with open("config.txt", "r") as f:
configParser = configparser.RawConfigParser()
configFilePath = r'config.txt'
configParser.read(configFilePath, encoding='utf-8')
rootPath = configParser.get('config', 'rootPath')
types = tuple(configParser.get('config', 'Types').split(','))
itemlist = []
for root, dirs, files in os.walk(rootPath):
for file in files:
if file.endswith(types):
full_path = os.path.join(root, file)
itemlist.append(full_path)
with open("db-file", "wb") as f:
pickle.dump(itemlist, f)
except FileNotFoundError:
QMessageBox.warning(self, '错误', '未找到config.txt文件')
return
self.cacheExists = True
self.cacheLabel.setText('缓存已建立')
self.cacheLabel.setStyleSheet('color: green')
def randomOpen(self):
if not self.cacheExists:
QMessageBox.warning(self, '错误', '请先建立文件列表缓存')
return
try:
with open("db-file", "rb") as f:
lines = pickle.load(f)
except FileNotFoundError:
QMessageBox.warning(self, '错误', '请先建立文件列表缓存')
return
file = random.choice(lines)
try:
os.startfile(file)
except FileNotFoundError:
QMessageBox.warning(self, '错误', '未找到对应文件')
return
self.openedFiles.insert(0, file)
self.openedFiles = self.openedFiles[:10]
self.updateOpenedFiles()
def updateOpenedFiles(self):
self.openedFileList.clear()
for file in self.openedFiles:
item = QListWidgetItem()
self.openedFileList.addItem(item)
btn = QPushButton('打开目录')
btn.clicked.connect(functools.partial(self.openDir, file))
btn1 = QPushButton('删除')
btn1.clicked.connect(functools.partial(self.deleteFile, file))
itemWidget = QWidget()
hLayout = QHBoxLayout(itemWidget)
hLayout.addWidget(btn)
hLayout.addWidget(btn1)
hLayout.addWidget(QLabel(os.path.basename(file)))
hLayout.setSizeConstraint(QHBoxLayout.SizeConstraint.SetFixedSize)
item.setSizeHint(itemWidget.sizeHint())
self.openedFileList.setItemWidget(item, itemWidget)
def openDir(self, file):
subprocess.run([FILEBROWSER_PATH, '/select,', file])
def deleteFile(self, filepath):
reply = QMessageBox.question(self, '确认', '确定删除该文件吗?',
QMessageBox.StandardButton.Yes|QMessageBox.StandardButton.No)
if reply == QMessageBox.StandardButton.Yes:
os.remove(filepath)
self.openedFiles.remove(filepath)
self.updateOpenedFiles()
if __name__ == '__main__':
app = QApplication([])
app.setApplicationName('RandPlay')
window = MyApp()
window.show()
window.raise_()
app.exec()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment