0

I am working on a basic calculator using PyQt5. I have a class to create buttons so I don't have to do it manually each time. I defined 16 functions, but I couldn't manage to attach these functions on the buttons using .format.

funclistq = ["sum", "takeaway", "multiply", "divide", "seven", "eight",
             "nine", "clear", "four", "five", "six", "zero", "one",
             "two", "three", "ok"]

for i in range(16):
  self.button.clicked.connect(self.{}.format(funclistq[i]))
musicamante
  • 41,230
  • 6
  • 33
  • 58
  • 1
    Not what you asked about, but could you explain the `self.{}` part to me? I'm not familiar with that syntax. – mypetlion Dec 17 '20 at 16:58
  • i guess that part is broken. i was trying to use format here and normally you need something like this : print( "if {} then {}".format("you are thirsty","drink some water") . i was trying to iterate through my list with that part. – Furkan Özdemir Dec 17 '20 at 17:05
  • unfortunately i can't use a string after "self." part. – Furkan Özdemir Dec 17 '20 at 17:16
  • So i think you have confused what format will do. format is to apply to strings. what you need to do is pass a handle to the function. (https://stackoverflow.com/questions/15080731/calling-a-function-upon-button-press) – Tom Myddeltyn Dec 17 '20 at 18:19

1 Answers1

1

.format() is only for strings. What you want is a dynamic attribute lookup, which you can do with getattr.

Also note that in Python, a for loop can loop directly over the items in a list, without having to use indices.

for func_name in func_list_q:
    func = getattr(self, func_name)
    self.button.clicked.connect(func)

On a somewhat related note: if you're on Python 3.6 or newer and using .format() for strings, I bet you'll really enjoy f-strings. They make formatting much more convenient and readable!

CrazyChucky
  • 3,263
  • 4
  • 11
  • 25
  • thanks for this answer. it really helped me since i know where to look at now. my project is a beginner one and i am trying to improve my coding skills with little tasks like this one. i went with a simple solution while waiting for an answer. `if i == 0 : self.button.clicked.connect(self.sum) elif i == 1 : self.button.clicked.connect(self.takeaway) elif i == 2 : self.button.clicked.connect(self.multiply)` etc. – Furkan Özdemir Dec 17 '20 at 17:28