简体   繁体   中英

how to pass a variable into a function connected to a button pyqt5 python

def open_browser(i):
            print("open")

 for i in range(5):
     new_name_label = 'name_label'+str(i)
     list_names.append(new_name_label)
     setattr(self, list_names[i], QPushButton(str(ordered_names[i]),self))
     exec(f'self.name_label{i}.setGeometry(250,{y_axis_name},340,110)')
     exec(f'self.name_label{i}.clicked.connect(open_browser({i}))')
     y_axis_name= y_axis_name + 110

"i" is a variable and I cant find a way to click the button self.name_label and then connect that to a function and pass in the variable "i". when i attempted to run it I get the error

错误图片

it seems that the variable "i" is not being replaced by one of the numbers in the range represented by "i" and instead i the letter is trying to be passed in.

If you want to assign function with argument then you can use lambda to create function without argument

connect( lambda:open_browser(i) )

but if you run it in loop then you may need also to copy value i to new variable.

connect( lambda x=i:open_browser(x) )

If you use directly i then all buttons will use reference to variable i , not values from i - and finally all buttons will get the same value - last value assigned to i in loop.


Code connect(open_browser(i)) works as

result = open_browser(i) 
connect(result)

and because def open_browser() doesn't use return so it automatically runs return None and your code works like

result = None
connect(result)

and you have

connect(None)

and later error shows Unexpected type "NoneType"


BTW:

If you use for -loop to create objects then better use list to keep these objects. It doesn't need exec() and it can be more useful later - because later you can use again for -loop to check all objects from list.

Besides it looks very strange when someone need exec() to create code.

self.buttons = []

for i in range(5):
     b = QPushButton(str(ordered_names[i]), self)
     b.setGeometry(250, y_axis_name, 340, 110)
     b.clicked.connect( lambda x=i:open_browser(x) )

     self.buttons.append( b )

     y_axis_name += 110     

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM