A toolbar for Python with Tkinter

In this script we will build a basic toolbar with:

  • buttons with images and text
  • a frame to contain the buttons

To add an image in a button:

  • load the image with PhotoImage
  • put image parameter referring to the PhotoImage object into the button parameters

The code

from tkinter import *
import glob
import os


def dic_imgs():
    imgs = {}
    for i in glob.glob("icons/*.png"):
        pathfile = i
        i = os.path.basename(i)
        name = i.split(".")[0]
        imgs[name] = PhotoImage(file=pathfile)
    return imgs


root = Tk()
root.geometry("400x400")
imgs = dic_imgs()

def callback():
    print("called the callback!")


toolbar = Frame(root)
toolbar.pack(side=TOP, fill=X)

b1 = Button(
    toolbar,
    relief=FLAT,
    compound = LEFT,
    text="new",
    command=callback,
    image=imgs["notepad"])
b1.pack(side=LEFT, padx=0, pady=0)

b2 = Button(
    toolbar,
    text="open",
    compound = LEFT,
    command=callback,
    relief=FLAT,
    image=imgs["github"])
b2.pack(side=LEFT, padx=0, pady=0)


mainloop()

Adjust the size of an icon

You better put the icons of the same size in your toolbar, but if you want to resize them within the code… use this example

from tkinter import *
import glob
import os


def dic_imgs():
    imgs = {}
    for i in glob.glob("icons/*.png"):
        pathfile = i
        i = os.path.basename(i)
        name = i.split(".")[0]
        imgs[name] = PhotoImage(file=pathfile)
        if name == "plus":
            imgs[name] = imgs[name].subsample(2)
    return imgs


root = Tk()
root.geometry("400x400")
imgs = dic_imgs()

def callback():
    print("called the callback!")


toolbar = Frame(root)
toolbar.pack(side=TOP, fill=X)

b1 = Button(
    toolbar,
    relief=FLAT,
    compound = LEFT,
    text="new",
    command=callback,
    image=imgs["notepad"])
b1.pack(side=LEFT, padx=0, pady=0)

b2 = Button(
    toolbar,
    text="open",
    compound = LEFT,
    command=callback,
    relief=FLAT,
    image=imgs["github"])
b2.pack(side=LEFT, padx=0, pady=0)

b2 = Button(
    toolbar,
    text="save",
    compound = LEFT,
    command=callback,
    relief=FLAT,
    image=imgs["plus"])
b2.pack(side=LEFT, padx=0, pady=0)

mainloop()

The repository for this script

The repository


Subscribe to the newsletter for updates
Tkinter templates

Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Claude's Games

Arkanoid
Platform 2d

1. Memory game

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Advertisement