[SOLVED] PyQt button with an image on it



  • 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]
    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_())
    

    [/code]



  • Set your image as an "icon":http://qt-project.org/doc/qt-4.8/qabstractbutton.html#icon-prop on your button and then set the buttons "iconSize":http://qt-project.org/doc/qt-4.8/qabstractbutton.html#iconSize-prop, something like:

    @
    ...
    self.button.setIcon(QIcon('./myImage.png'))
    self.button.setIconSize(QSize(24,24))
    ...
    @

    Hope this helps ;o)



  • I've added it in

    [code]
    class Window(QtGui.QWidget):
    def init(self):
    QtGui.QWidget.init(self)
    self.button = QtGui.QPushButton('', self)
    self.button.setIcon(QIcon('c:\Itllworkthistime\z.jpeg'))
    self.button.setIconSize(QSize(24,24))
    self.button.clicked.connect(self.handleButton)
    layout = QtGui.QVBoxLayout(self)
    layout.addWidget(self.button)
    [/code]

    but when I run it, I get this message:

    [code]
    Traceback (most recent call last):
    File "C:\Itllworkthistime\email button.py", line 33, in <module>
    window = Window()
    File "C:\Itllworkthistime\email button.py", line 11, in init
    self.button.setIcon(QIcon('c:\Itllworkthistime\z.jpeg'))
    NameError: global name 'QIcon' is not defined
    [/code]



  • My apologies, try the following:

    @
    self.button.setIcon(QtGui.QIcon(''c:/Itllworkthistime/z.jpeg''))
    self.button.setIconSize(QtCore.QSize(24,24)
    @

    Assuming you have:

    @
    from PyQt4 import QtGui, QtCore
    @

    Hope this helps ;o)



  • I do have
    [code] from PyQt4 import QtGui, QtCore [/code]
    It says it's invalid syntax then highlights the "c" from c:/Itllworkthistime/z.jpeg
    Then if I take the double apostrophes out to highlight it in green, it comes up with the same error and highlights the "self" from
    [code] self.button.clicked.connect(self.handleButton) [/code]



  • My bad (typo), the path should just be a normal python string i.e. "c:/Itllworkthistime/z.jpeg".



  • It's still highlighting the "self" in red, which is really weird, because it wasn't before :S



  • Missing bracket:
    @
    self.button.setIconSize(QtCore.QSize(24,24))
    @



  • And if I take out
    [code] self.button.clicked.connect(self.handleButton) [/code]
    it says that layout in the line below it is invalid syntax :S



  • Ahhh c:
    Now I'm getting a new error when I run it:
    [code]
    Traceback (most recent call last):
    File "C:\Itllworkthistime\email button.py", line 32, in <module>
    window = Window()
    File "C:\Itllworkthistime\email button.py", line 10, in init
    self.button.setIcon(QtGui.QIcon("c:/Itllworkthistime/z.jpeg"))
    AttributeError: 'Window' object has no attribute 'button'
    [/code]



  • We're making quite heavy weather of this! The following works fine on my system (with a different image file obviously):

    @
    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)
    self.button.setIcon(QtGui.QIcon("c:/Itllworkthistime/z.jpeg"))
    self.button.setIconSize(QtCore.QSize(24,24))
    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_())
    

    @



  • Ah :L
    I accidentally deleted the line
    [code]
    self.button = QtGui.QPushButton('', self)
    [/code]
    It's working now, but the image isn't there :c



  • Check the name of and the path to the image is correct. If its in the same folder as your python script just use a relative path:

    @
    ...
    self.button.setIcon(QtGui.QIcon("./z.jpeg"))
    ...
    @



  • It was a .jpg rather than a .jpeg apparently =]
    Thank you so much ^_^

    If you can help me some more though I'd appreciate it because I've just been told to add a sound for when the button gets clicked, how do I do that? =]
    And I've got this extended version of the email script that I half pinched from a tutorial and half wrote myself that sends a gif with html, but I can't seem to get it working:

    [code]
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.image import MIMEImage

    me = "swilliams@brecon-hs.powys.sch.uk"
    you = "ajames@brecobn-hs.powys.sch.uk"

    msg = MIMEMultipart('related')
    msg['Subject'] = 'Test Message'
    msg['From'] = me
    msg['To'] = you
    msg.preamble = 'This is a super cool multipart message using html and python c:'

    msgAlt = MIMEMultipart('alternative')
    msg.attach(msgAlt)

    msgTxt = MIMEText('You see this if it fails')
    msgAlt.attach(msgTxt)

    thehtmlcode = """
    <html>
    <head>Test Header</head>
    <body>
    <p>This isn't plain text!<br>
    If you're seeing this everything should be working as planned :D<br>
    Here's the gif <a href="http://tinypic.com?ref=2wpnfnt" target="_blank"><img src="http://i43.tinypic.com/2wpnfnt.gif" border="0" alt="Image and video hosting by TinyPic"></a>
    </p>
    </body>
    </html>
    """
    msgTxt = MIMEText(thehtmlcode, msgAlt.attach(msgTxt))

    fp = open('coffee.gif', 'r')
    msgImg = MIMEImage(fp.read())
    fp.close()

    msgImg.add_header('EMEGRENCY thing', '<Itsapicture>')
    msg.attach(msgImg)

    smtp = smtplib.SMTP('BHS-MAIL')
    s.send_message(msg)
    [/code]

    When I run it I get this error message

    [code]
    Traceback (most recent call last):
    File "C:\Users\ACERREVO\Desktop\New folder\Awesomegifworksscript.py", line 36, in <module>
    msgImg = MIMEImage(fp.read()) #something's wrong here.
    File "C:\Python33\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
    UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 206: character maps to <undefined>
    [/code]



  • The "#something's wrong here." in the error message I put in then took out to post, because I wanted to remind myself that it was the line referred to in the error message =]



  • The following example plays a sound when the button is pressed:

    @
    from PyQt4.QtCore import *
    from PyQt4.QtGui import *
    from PyQt4.phonon import Phonon

    class Widget(QWidget):
    def init(self, parent=None, **kwargs):
    QWidget.init(self, parent, **kwargs)

        l=QVBoxLayout(self)
        l.addWidget(QPushButton("Play", self, clicked=self.play))
    
    def play(self):
        self.output=Phonon.AudioOutput(Phonon.MusicCategory)
        self.media=Phonon.MediaObject()
        Phonon.createPath(self.media, self.output)
        self.media.setCurrentSource(Phonon.MediaSource('./sound_file.wav'))
        self.media.play()
    

    if name=="main":
    from sys import argv, exit

    a=QApplication(argv)
    w=Widget()
    w.show()
    w.raise_()
    exit(a.exec_())
    

    @

    You'll need the Phonon module installed for this to work (and provide your own sound file ;o).

    For your other problem, try the following for line 34:

    @
    fp = open('coffee.gif', 'rb')
    @

    This opens the file in binary rather than ASCII mode.

    Also, if your original problem is solved, please insert [SOLVED] into the threads title to mark it as such.



  • I've changed that, it's working now :D
    Only it's sending the plain text alternative instead of the html =/

    And thank you for the sound script, I'll have a play around with it now :D
    Where would I get Phonon from though? =]


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.