PyQt connect method bug when used in a for loop which creates widgets from a list

StackOverflow https://stackoverflow.com/questions/736651

  •  09-09-2019
  •  | 
  •  

Question

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
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top