PyQt button with an image on it

Post here if you need help with creating a Graphical User Interface in Python.

PyQt button with an image on it

Postby Swilliams » Wed May 22, 2013 11:47 am

I'm making a button that sends an email, it's all working, but I want to change the size of the button and put an image on it, what lines would I add to my code and where? =]

Code: Select all
from PyQt4 import QtGui, QtCore

import smtplib

from email.mime.text import MIMEText

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.button = QtGui.QPushButton('', self)
        self.button.clicked.connect(self.handleButton)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.button)

    def handleButton(self):
        fp = open('Firetruck.txt', 'r')
        msg = MIMEText(fp.read())
        fp.close()

        msg['Subject'] = 'Subject'
        msg['From'] = 'ajames@brecon-hs.powys.sch.uk'
        msg['To'] = 'swilliams@brecon-hs.powys.sch.uk'

        s = smtplib.SMTP('BHS-MAIL')
        s.send_message(msg)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())
Swilliams
 
Posts: 4
Joined: Tue May 21, 2013 11:10 am

Re: PyQt button with an image on it

Postby metulburr » Wed May 22, 2013 9:41 pm

A method would be to make a QLabel clickable
Code: Select all
import sys
from PyQt4 import QtCore, QtGui
 
class ExtendedQLabel(QtGui.QLabel): 
 
    def __init(self, parent): 
        QLabel.__init__(self, parent) 
 
    def mouseReleaseEvent(self, ev): 
        self.emit(QtCore.SIGNAL('clicked()'))

 
class MainUI(QtGui.QWidget): 
    BUTTON_IMAGE = '/home/metulburr/Pictures/arrow2.jpeg' 
 
    def __init__(self, *args):   
        QtGui.QWidget.__init__(self) 
        self.resize(350, 140) 
        self.initButton() 
        self.connect(self.ImageButton, QtCore.SIGNAL('clicked()'), self.buttonClicked) 
 
    def initButton(self): 
        self.ImageButton = ExtendedQLabel(self) 
        self.ImageButton.move(0,0) 
        self.ImageButton.setPixmap(QtGui.QPixmap(self.BUTTON_IMAGE)) 
 
    def buttonClicked(self): 
        print('Button Clicked') 
       
if __name__ == "__main__":

    app = QtGui.QApplication(sys.argv)
    window = MainUI()
    window.show()
    sys.exit(app.exec_())


PS. moved your thread to GUI
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1470
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY


Return to GUI

Who is online

Users browsing this forum: No registered users and 2 guests