0

I use PyQt5 for GUI programming. And I use QPushbutton and connect slots with lambda functions.

cz i need to use several buttons repeatedly, i want use for-loop to shorten code. But result is different when using for-loop or not.

the code is,

openFile_1_1.clicked.connect(lambda: self.btn_openFile(1, 1))
openFile_1_2.clicked.connect(lambda: self.btn_openFile(1, 2))
openFile_2_1.clicked.connect(lambda: self.btn_openFile(2, 1))
openFile_2_2.clicked.connect(lambda: self.btn_openFile(2, 2))
openFile_3_1.clicked.connect(lambda: self.btn_openFile(3, 1))
openFile_3_2.clicked.connect(lambda: self.btn_openFile(3, 2))
openFile_4_1.clicked.connect(lambda: self.btn_openFile(4, 1))
openFile_4_2.clicked.connect(lambda: self.btn_openFile(4, 2))
openFile_5_1.clicked.connect(lambda: self.btn_openFile(5, 1))
openFile_5_2.clicked.connect(lambda: self.btn_openFile(5, 2))
openFile_6_1.clicked.connect(lambda: self.btn_openFile(6, 1))
openFile_6_2.clicked.connect(lambda: self.btn_openFile(6, 2))
openFile_7_1.clicked.connect(lambda: self.btn_openFile(7, 1))
openFile_7_2.clicked.connect(lambda: self.btn_openFile(7, 2))

-----------------------------------------------------------------------------------

    def btn_openFile(self, i, j):
        fname = QFileDialog.getOpenFileName(self, 'Open file', './')

        globals()['file_name_{}_{}'.format(i, j)].setText(fname[0])

using for-loop, I am trying to shorten that code. I used for-loop like this,

for i in range(1, 8):
    for j in range(1, 3):
        globals()['openFile_{}_{}'.format(i, j)].clicked.connect(lambda: self.btn_openFile(i, j))

-----------------------------------------------------------------------------------

    def btn_openFile(self, i, j):
        fname = QFileDialog.getOpenFileName(self, 'Open file', './')

        globals()['file_name_{}_{}'.format(i, j)].setText(fname[0])

I want connect 'openFile_{}{}' variables to each 'file_name{}_{}' variables.

but when using for-loop, all variables(openFile_1_1 ~ opneFile_7_2) are connected to file_name_7_2 variable.

I wonder how to fix my code.

LCS
  • 1
  • 2
  • First of all, don't use globals for that, especially if you're trying to access variables by using dynamic values. Then, don't use globals at all, unless you **really** know how to use them and what they are for (hint: if you know their behavior and purpose, 99% of the times you wouldn't even think to use them for something like this). I strongly suggest you to read more about classes, instances, methods and attributes, and then be aware that most of the times you don't need to (or won't) use attribute names to access objects. – musicamante Feb 18 '23 at 04:17

0 Answers0