欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

pyqt5实现按钮添加背景图片以及背景图片的切换方法

时间:2021-09-01 09:01:03|栏目:Python代码|点击:

简介

对与控件QPushButton中的可以使用setStyleSheet设置它背景图片。具体设置背景图片的方法有两种

self.button.setStyleSheet("QPushButton{background-image: url(img/1.png)}")

然而对于这种方法背景图片无法进行边框的自适应,可以使用下面的方法

self.button.setStyleSheet("QPushButton{border-image: url(img/1.png)}")

可以做到自适应边框。

代码

代码里面有两个图片需要使用,我放在下面了

代码1

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
 
class Example(QWidget):
 
 def __init__(self):
  super().__init__()
 
  self.initUI() # 界面绘制交给InitUi方法
 
 def initUI(self):
  # 设置窗口的位置和大小
  self.setGeometry(300, 300, 300, 220)
  # 设置窗口的标题
  self.setWindowTitle('QPushButton')
 
  #控件QPushButton的定义和设置
  self.button = QPushButton(self)
  self.button.setStyleSheet("QPushButton{border-image: url(img/1.png)}"
         "QPushButton:hover{border-image: url(img/1_1.png)}" 
         "QPushButton:pressed{border-image: url(img/1_1.png)}")
  #设置控件QPushButton的位置和大小
  self.button.setGeometry(100, 100, 50, 50)
 
 
 
 
if __name__ == '__main__':
 # 创建应用程序和对象
 app = QApplication(sys.argv)
 ex = Example()
 ex.show()
 sys.exit(app.exec_())

具体实现了按钮背景图片,以及鼠标划过按钮的背景切换,以及按下按钮的背景切换。

然而在按下按钮,我需要直接进行图片切换,且不回到原来的背景上。可以参考我的代码2。

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
 
 
class Example(QWidget):
 
 def __init__(self):
  super().__init__()
 
  self.initUI() # 界面绘制交给InitUi方法
  self.slot_init()
 
 def initUI(self):
  # 设置窗口的位置和大小
  self.setGeometry(300, 300, 300, 220)
  # 设置窗口的标题
  self.setWindowTitle('QPushButton')
 
  #控件QPushButton的定义和设置
  self.button = QPushButton(self)
  self.button.setStyleSheet("QPushButton{border-image: url(img/1.png)}"
         "QPushButton:hover{border-image: url(img/1_1.png)}")
 
  # 设置控件QPushButton的位置和大小
  self.button.setGeometry(100, 100, 50, 50)
 
 def slot_init(self):
  self.button.clicked.connect(self.button_change)
 
 def button_change(self):
  # 切换图标变亮
  self.button.setStyleSheet('QPushButton{border-image:url(img/1_1.png)}')
 
 
 
if __name__ == '__main__':
 # 创建应用程序和对象
 app = QApplication(sys.argv)
 ex = Example()
 ex.show()
 sys.exit(app.exec_())

如果需要来回的切换,可以定义一个计数器来解决这个问题。

上一篇:python操作mysql、excel、pdf的示例

栏    目:Python代码

下一篇:Python实现检测文件MD5值的方法示例

本文标题:pyqt5实现按钮添加背景图片以及背景图片的切换方法

本文地址:http://www.codeinn.net/misctech/171671.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有