Buttons with Images created on the go

A little script to show how to make a new image and use it to make a fun button in tkinter.

The output is this:

import tkinter as tk
from PIL import Image, ImageDraw, ImageTk, ImageFont


def create_image():
    "Use a new image for the button"
    width = 160
    im = Image.new("RGBA", (width, 20), "red")
    d = ImageDraw.Draw(im)
    d.text((
        0, 0),
        "Click on this button",
        font=ImageFont.truetype("arial", 18), fill="blue")
    d.line((0,2,width,2), fill="yellow")
    d.line((0,18,width,18), fill="yellow")
    img = ImageTk.PhotoImage(im)
    img.image = img
    b = tk.Button(
        root,
        bd=0,
        relief="groove",
        compound=tk.CENTER,
        text="",
        image=img
    )
    b.pack()


root = tk.Tk()
root.title("Buttons")
create_image()
root.mainloop()


Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.