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
Subscribe to the newsletter for updates
Tkinter templatesTwitter: @pythonprogrammi - python_pygame
Claude's Games
1. Memory gameVideos
Speech recognition gamePygame's Platform Game