In this tutorial, we are going to learn how to add menu items to a push button with PyQt5 in Python.

A menu button, which in some styles will produce a small triangle to the right of the button’s text. Adding menu to a push button a great alternative to create a pop-up menus or shortcuts.

Buy Me a Coffee? Your support is much appreciated!
PayPal Me:
Venmo: @Jie-Jenn

window.adsbygoogle || []).push({});

Source Code:

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

class AppDemo(QWidget):
    def __init__(self):

        states_cities = [
            {'California': ['San Francisco', 'Oakland', 'San Jose', 'San Mateo']},
            {'Illinois': ['Chicago', 'Evanston', 'Springfield']},

        btn = QPushButton('Click Me', self)
        btn.move(100, 100)
        btn.resize(150, 150)

        menu = QMenu()
        menu.triggered.connect(lambda x: print(x.text()))

        self.add_menu(states_cities, menu)

    def add_menu(self, data, menu_obj):
        if isinstance(data, dict):
            for k, v in data.items():
                sub_menu = QMenu(k, menu_obj)
                self.add_menu(v, sub_menu)
        elif isinstance(data, list):
            for element in data:
                self.add_menu(element, menu_obj)
            action = menu_obj.addAction(data)

app = QApplication(sys.argv)        
demo = AppDemo()