Home > Software design >  tkinter toolbar menu/ button open drop-down menu/gif
tkinter toolbar menu/ button open drop-down menu/gif

Time:02-25

In the toolbar I press a button and a drop-down menu with buttons opens. The images are. gif for buttons. I want the button in the toolbar to open a drop-down menu with buttons (image - gif). How can I do this?

# Image Toolbar
img1 = PhotoImage(file = r\path\"img.gif")`

# Toolbar 
toolbar = Frame(root, bd=1, relief=RAISED) 
toolbar.pack(side=TOP, fill=X)

btn1 = Button(toolbar, relief=FLAT, compound= LEFT, text="",image=img1, command=submenu1)
btn1.pack(side=LEFT, padx=0, pady=0)

def submenu1():
    # gif icon for submenu1:
    imgvar1 = PhotoImage(file=r\path\.gif)
    ???

CodePudding user response:

To make a button with a drop-down menu I suggest you use a Menubutton which was designed for that purpose — it's the part that stays on the screen all the time. After creating one you should create a Menu widget and configure the Menubutton to use it.

Once you have a Menu instance, you can populate it with different kinds of menu items, including ones made of images by using the Menu.insert_cascade() method. Also see this Menu item creation documentation which describes all the different kinds of menu items you can create and add to one.

Below is some sample code illustrating what I mean. For simplicity I used the same image twice — on the Menubutton and on one of the items on the drop-down menu that is displayed when it's clicked.

import tkinter as tk
from tkinter.constants import *

root = tk.Tk()

# Image Toolbar
img1 = tk.PhotoImage(file="8-ball.png")

# Toolbar
toolbar = tk.Frame(root, bd=1, relief=RAISED)
toolbar.pack(side=TOP, fill=X)

menubtn = tk.Menubutton(toolbar, relief=FLAT, compound=LEFT, text="", image=img1)
menubtn.pack(side=LEFT, padx=0, pady=0)

menu = tk.Menu(menubtn, tearoff=0)
menubtn.config(menu=menu)

menu.insert_command(0, label='Submit', command=lambda: print('Submit clicked'))

imgvar1 = tk.PhotoImage(file="8-ball.png")
menu.insert_cascade(1, image=imgvar1, command=lambda: print('Image pop out clicked'))

root.mainloop()

  • Related