简体   繁体   English

获取 PyQT5 中的按钮名称

[英]Getting the button name in PyQT5

I'm working on a simple tic-tac-toe game with gui using PyQt5.我正在使用 PyQt5 使用 gui 开发一个简单的井字游戏。 The interface is all set up but I'm having a bit of trouble with a function.接口已全部设置,但我在使用 function 时遇到了一些问题。 The interface is a 3x3 grid of buttons.该界面是一个 3x3 的按钮网格。 When you click one of these buttons, it dropsdown a choice of X or O. Whichever choice you click on, that becomes the text of the button.当您单击其中一个按钮时,它会下拉选择 X 或 O。无论您单击哪个选项,它都会成为按钮的文本。

class App(QMainWindow):
    game_board = {
        'btn1': '', 'btn2': '', 'btn3': '',
        'btn4': '', 'btn5': '', 'btn6': '',
        'btn7': '', 'btn8': '', 'btn9': ''
    }

    def __init__(self):
        super().__init__()
        self.title = 'Tic-Tac-Toe'
        self.top = 100
        self.left = 100
        self.width = 375
        self.height = 375
        
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.top, self.left, self.width, self.height)

...___...

        # buttons that make up the gameboard
        self.btn1 = QPushButton(self.game_board['btn1'], self)
        self.btn2 = QPushButton(self.game_board['btn2'], self)
        self.btn3 = QPushButton(self.game_board['btn3'], self)
        self.btn4 = QPushButton(self.game_board['btn4'], self)
        self.btn5 = QPushButton(self.game_board['btn5'], self)
        self.btn6 = QPushButton(self.game_board['btn6'], self)
        self.btn7 = QPushButton(self.game_board['btn7'], self)
        self.btn8 = QPushButton(self.game_board['btn8'], self)
        self.btn9 = QPushButton(self.game_board['btn9'], self)

        self.btns = {'btn1': self.btn1, 'btn2': self.btn2, 'btn3': self.btn3, 'btn4': self.btn4, 'btn5': self.btn5, 'btn6': self.btn6, 'btn7': self.btn7, 'btn8': self.btn8, 'btn9': self.btn9}

        x_o_menu = QMenu(self)
        x_o_menu.addAction('X', self.x_action)
        x_o_menu.addAction('O', self.o_action)
        
        i = 1

        for value in self.btns.values():
            if i < 4:
                value.setGeometry(75*i, 75, 75, 75)
            elif i < 7:
                value.setGeometry(75*(i-3), 150, 75, 75)
            elif i < 10:
                value.setGeometry(75*(i-6), 225, 75, 75)

            i += 1

            value.setMenu(x_o_menu)
        
        self.show()

...___...

    def x_action(self):
        sender = self.sender()
        self.statusBar().showMessage(sender.text() + ' was pressed')

    def o_action(self):
        pass

The closest solution I've found so far has been to use self.sender() but that doesn't return the button, rather it returns the dropdown option (which as I'm typing this I realize I could probably use to turn x_action and o_action into a single method), but I still have no way of knowing which button to update the text for.到目前为止我发现的最接近的解决方案是使用 self.sender() 但这不会返回按钮,而是返回下拉选项(当我输入这个时,我意识到我可能会用它来打开 x_action和 o_action 合并为一个方法),但我仍然无法知道要为哪个按钮更新文本。 Is there a way to do this without giving a unique menu to each button?有没有办法在不为每个按钮提供唯一菜单的情况下做到这一点?

A QMenu, just like a QAction, can be shown/used by any parent. QMenu,就像 QAction 一样,可以被任何父母展示/使用。 It can also be shown without any actual parent.它也可以在没有任何实际父级的情况下显示。 So your approach is actually invalid.所以你的方法实际上是无效的。

Since your board will clearly have a limited range of buttons, adding a unique menu to each button won't create that big overhead, so a possibility is to create individual menus for each button.由于您的电路板显然具有有限范围的按钮,因此为每个按钮添加一个独特的菜单不会产生那么大的开销,因此可以为每个按钮创建单独的菜单。

A better approach, though, would be to create a subclass of QPushButton and add a unique QMenu for that button.不过,更好的方法是创建 QPushButton 的子类并为该按钮添加一个唯一的 QMenu。 Then you need to create a custom signal for the button class, and you can connect that signal from the main program using the custom signature or, eventually, a lambda.然后您需要为按钮 class 创建一个自定义信号,您可以使用自定义签名或最终使用 lambda 从主程序连接该信号。

Please note that creating direct child widgets for a QMainWindow is discouraged, as well as using fixed geometries;请注意,不鼓励为 QMainWindow 创建直接子窗口小部件以及使用固定几何图形; as the documentation suggests :正如文档所示

Note: Creating a main window without a central widget is not supported.注意:不支持创建没有中央小部件的主 window。 You must have a central widget even if it is just a placeholder.即使它只是一个占位符,您也必须有一个中央小部件。

You should properly create a central widget (a basic QWidget would suffice), then use setCentralWidget() and set up a layout manager for that central widget.您应该正确地创建一个中央小部件(一个基本的 QWidget 就足够了),然后使用setCentralWidget()并为该中央小部件设置一个布局管理器 Then , you can add the buttons to that layout.然后,您可以将按钮添加到该布局。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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