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]))
.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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.