tags:

views:

264

answers:

1

I have a GUI program,

It auto create buttons from a name list, and connect to a function prints its name.

but when I run this program, I press all the buttons,

they all return the last button's name.

I wonder why this thing happens. can any one help?

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import logging

logging.basicConfig(level=logging.DEBUG,)

class MainWindow(QWidget):
    def init(self):
        names = ('a','b','c')
        lo = QHBoxLayout(self)
        for name in names:
            button = QPushButton(name,self)
            lo.addWidget(button)
            self.connect(button,SIGNAL("clicked()"),
                         lambda :logging.debug(name))

if __name__=="__main__":
    app = QApplication(sys.argv)
    m = MainWindow();m.init();m.show()
    app.exec_()

result like:

python t.py
DEBUG:root:c
DEBUG:root:c
DEBUG:root:c
+2  A: 

I see at least one bug in your code.

Replace:

 lambda :logging.debug(name)

By:

 lambda name=name: logging.debug(name)

See Why results of map() and list comprehension are different? for details.

J.F. Sebastian