Tkinter and how to add an image to a button

Let’s continue the post I made lately about a launcher of applications made with python and lets also see how to add an image to a tkinter (ttk also) button. It is a little tricky (there’s a trick that I will struggle to find in the video of the live coding below), so … enjoy the live coding of this.

What if you want an image in the button?

I thought that the interface could be nicer with some images in the button, so there code is to do it.

import os
import tkinter as tk
import tkinter.ttk as ttk


root = tk.Tk()
root.title("Lanch my Programs")
root.geometry("400x400")

class Button:
    """button1 = Button("Testo", "4ce", 0, 0)"""
    def __init__(self, text, classe, func, row, col, image=""):
        image2 = tk.PhotoImage(file=image)
        image3 = image2.subsample(1, 1)
        self.button = ttk.Button(
            root,
            text=text,
            image=image3,
            compound = tk.LEFT,
            command=lambda: func(classe))
        # self.button.pack()
        self.button.grid(row=row, column=col, sticky=tk.NW, pady=0)
        self.button.image = image3

    def open_text(text):
        os.startfile(text)


print(os.getcwd())
Button("Open example text", "", lambda x: Button.open_text("example_for_launch.txt"), 0, 0, image="notepad.PNG")
Button("Open example text 2", "", lambda x: Button.open_text("Hello World 2.txt"), 1, 0,  image="notepad.PNG")


root.mainloop()

and here is the result:


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.