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
linjunhalida
  • 4,538
  • 6
  • 44
  • 64

1 Answers1

3

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.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670