【问题标题】:Assign multiple functions to a button [duplicate]将多个功能分配给一个按钮[重复]
【发布时间】:2021-06-30 05:09:26
【问题描述】:

我想为一个按钮分配多个功能,但是当我这样做时,它不会更改按钮文本,而是执行第二个功能。当我只连接 setText 函数时,它会编辑文本。那是被剪掉的代码:

ui.button_start.clicked.connect(lambda: ui.button_start.setText("Stop"))
ui.button_start.clicked.connect(lambda: bot.accept_request(loop=True))

我已经在网上搜索过,他们说应该可以,但是不行:(

我想我也不得不说accept_request()在chromedriver中打开一个URL,但奇怪的是即使我在Selenium调用之前调用editText函数它也不会编辑文本(Selenium调用有效)。

【问题讨论】:

  • 你为什么有tkinter标签?

标签: python user-interface pyqt pyqt5


【解决方案1】:

你可以试试这个,有两行:

import sys
from PyQt5.QtWidgets import QPushButton, QApplication, QWidget


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        btn = QPushButton(self, text="Hello World")

        # This, with two lines
        btn.clicked.connect(self.func_1)
        btn.clicked.connect(self.func_2)

    def func_1(self):
        print("The Button Was Clicked! (Function 1)")

    def func_2(self):
        print("The Button Was Clicked! (Function 2)")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())

这比编写一个调用另外两个函数的函数要干净得多。

【讨论】:

  • 这就是我所做的,但它仍然不起作用(我还编辑了我的问题)
  • 这一直对我有用,你能试试这个代码 sn-p 吗(在没有其他代码的情况下单独尝试它是否有效)?这样我们就可以尝试缩小问题的范围。
  • @falk2 然后提供minimal reproducible example
【解决方案2】:

您可以编写第三个函数来调用另外两个函数并让按钮只执行helper 函数:

def helper():
   ui.button_start.setText("Stop")
   bot.accept_request(loop=True)

ui.button_start.clicked.connect(helper)

【讨论】:

  • 它仍然不起作用(我编辑了我的问题)
  • @falk2 然后提供minimal reproducible example
  • @ArcKoor lambda 是不必要的,使用 ui.button_start.clicked.connect(helper)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-16
相关资源
最近更新 更多