【发布时间】:2023-03-30 20:45:01
【问题描述】:
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”是一个变量,我找不到单击按钮 self.name_label 然后将其连接到函数并传入变量“i”的方法。当我尝试运行它时,我得到了错误
似乎变量“i”没有被替换为“i”表示的范围内的数字之一,而是试图传入 i 字母。
【问题讨论】:
-
你为什么使用
exec? -
始终将代码、数据和完整的错误消息作为文本(不是屏幕截图,不是链接)放在有问题的地方(不在评论中)。它将更具可读性,更多人会看到它 - 所以更多人可以帮助你。
-
self.name_label不是Button而是正常的string- 你不能点击它` -
如果你想要很多按钮,那么使用列表
self.name_label = []代替变量name_label1、name_label2- 并使用append()将按钮添加到列表中。它不需要使用exec(),它会比分隔变量更有用 -
肯定你不能使用
connect(open_browser(i)),因为它会首先运行result = open_browser(i),然后是connect(result),所以它会尝试将button与result连接起来,而不是与open_browser(i)功能连接