用户:
快乐的坤坤QWQ查看:0 回复:1 评论:0 创建时间:2021-02-04T15:29:03
【作品展示】

【作品介绍】
play us
【作品源代码】
import sys
from PySide2.QtCore import*
from PySide2.QtGui import *
from PySide2.QtWidgets import *
from ui_cards import Ui_Cards
class MyCards(QMainWindow,Ui_Cards):
def __init__(self):
super().__init__()
self.setupUi(self)
self.init_button()
self.init_img()
self.show()
#记录按钮点击次数
self.clicked_num=0
#绑定信号与槽函数
self.pbtn_img.buttonClicked.connect(self.pbtn_func)
#储存两个按钮和对应的图片
self.match_img={
1:{
"pbtn":None,
"pbtn_img":None
},
2: {
"pbtn": None,
"pbtn_img": None
},
}
def init_button(self):
pbtn_list=self.pbtn_img.buttons()
for btn in pbtn_list:
btn.setText("")
btn.setIcon(QIcon("bg.png"))
btn.setIconSize(QSize(150,150))
#设置按钮在选中和在未选中状态
btn.setCheckable(True)
def init_img(self):
import os
import random
#常见的图片类型
images_type=[".png",".jpg",".bmp",".jpeg"]
files=os.listdir("images")
all_imgs=[]
for file in files:
ext=os.path.splitext(file)[-1]
if ext in images_type:
all_imgs.append("images"+os.sep+file)
#生成乱序前16张图片
random_imgs=random.sample(all_imgs,6)
grid_imgs=random_imgs+random_imgs
random.shuffle(grid_imgs)
#图片与网格对应
pbtn_list=self.pbtn_img.buttons()
self.grids=dict(zip(pbtn_list,grid_imgs))
def pbtn_func(self):
if self.clicked_num<2:
QApplication.processEvents()
pbtn=self.pbtn_img.checkedButton()
#按钮点击次数自增1
self.clicked_num+=1
#显示按钮对应的图片
pbtn.setIcon(QIcon(self.grids[pbtn]))
#禁用按钮
pbtn.setEnabled(False)
#储存按钮对应得图片
self.match_img[self.clicked_num]["pbtn"]=pbtn
self.match_img[self.clicked_num]["pbtn_img"]=self.grids[pbtn]
#延时500ms
timer=QTimer()
timer.singleShot(500,self.judge)
def judge(self):
#判断图片是否配对
if self.clicked_num==2:
#重置按钮点击次数为0
self.clicked_num=0
#判断是否相同
if self.match_img[1]["pbtn_img"]!=self.match_img[2]["pbtn_img"]:
#设置未配对的两个按钮的启动状态
self.match_img[1]["pbtn"].setEnabled(True)
self.match_img[2]["pbtn"].setEnabled(True)
#恢复显示默认的背景图片
self.match_img[1]["pbtn"].setIcon(QIcon("bg.png"))
self.match_img[2]["pbtn"].setIcon(QIcon("bg.png"))
if __name__=="__main__":
app=QApplication(sys.argv)
window=MyCards()
sys.exit(app.exec_())
【提示】
部分含有Python第三方库相关内容的作品,在海龟编辑器网页端无法运行哦!如遇到这种情况,可以打开下面的链接,下载海龟编辑器客户端:
https://python.codemao.cn