Python Tkinter section

A MenuButton to do Stuff

Post by Amina Delali, July 17th, 2023

Description

The MenuButton TK widget is used to create menus with the MenuButton as the visible part of it. It looks like a button, but when you click on it, you can dropdown a menu of choices that you have previously created. To do so, you have to create and associate a menu to the MenuButton, then you can; from that menu, add other options that can be simple clickable button, or even check buttons. In our case, we will create check buttons to change properties of an other button widget.
Three elements that worth mentioning from the code:

  • Creating the MenuButton: calling the Menubutton function will automatically create the widget. But, we have to create also a Menu, and assign this menu to the "menu" attribute of the widget
    Create a MenuButton TK Widget
  • Adding CheckButtons to the menu of the widget, simply by calling the add_checkbutton menu method. While adding the checkbuttons, we can specify the functions to call each time the checkbutton is checked or unchecked.
    Add checkbuttons to the menu of a menubutton widget
  • Defining the functions to be called when the user click on the checkbuttons. The functions name will be the values of the command properties of the checkbuttons.
    Define functions to be called when the user click on a menubutton option

In the code below, we will use the MenuButton to change two properties:

  • The background color of a created Button widget
  • The border width of that same button


The Code

from tkinter import *


main_window=Tk()
main_window.title("A MenuButton")
main_window.geometry('500x250+400+100'
main_window.configure(bg="#8800FF")


but =Button(main_window,text="Configurable",bg="#8800FF",border=0,width=50)
but.grid(row=0,column=0,padx=30,pady=30,columnspan=6)

mb=  Menubutton main_windowtext="Change Button's Appearance"
                     background="pink")
mb.grid(row=1,column=5,pady=30,padx=20)
mb.menu =  Menu mbtearoff 0)
mb["menu"] =  mb.menu


bgcVar IntVar()
bwVar IntVar()

def addBGC():
    if but["bg"]!="#bd9b16":
        but.configure(bg="#bd9b16")
    else:
         but["bg"]="#8800FF"

def addBW():
    if but["border"]!=5:
        but.configure(border=5)
    else:
        but.configure(border=0)

    

mb.menu.add_checkbutton label="Background Color",
                          variable=bgcVar,commandaddBGC)


mb.menu.add_checkbutton label="Border",
                          variable=bwVarcommand=addBW )
mb.menu.add

main_window.mainloop()

The Output



Something to say?

If you want to add something about this post, please feel free to do it by commenting below 🙂.