Makogan
Makogan

Reputation: 9538

How can you have a background image with text on top on a button on tk?

I am trying to make tk buttons look better by adding a button background. The issue is, I can use an image or text, but not both, for a tk button.

How can you have both?

This is what I have tried:

from tkinter import *
from PIL import Image, ImageTk

print("I ran")

master = Tk()

canvas_width = 800
canvas_height = 400
window = Canvas(master, 
           width=canvas_width,
           height=canvas_height)

img = Image.open("images/button_black.png").resize((80,40))
ph_image = ImageTk.PhotoImage(img)

l = Label(master, text='Button', image=ph_image, compound=CENTER, fg="white")
l.pack(side=LEFT)

button = Button ( master, image=l)

window.pack()

mainloop()

Upvotes: 0

Views: 2465

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386010

To use both an image and text you must set the compound option. From the canonical documentation:

Specifies if the widget should display text and bitmaps/images at the same time, and if so, where the bitmap/image should be placed relative to the text. Must be one of the values none, bottom, top, left, right, or center. For example, the (default) value none specifies that the bitmap or image should (if defined) be displayed instead of the text, the value left specifies that the bitmap or image should be displayed to the left of the text, and the value center specifies that the bitmap or image should be displayed on top of the text.

Example:

The following example uses this image:

enter image description here

The program renders like this when using compound="center":

enter image description here

import tkinter as tk

image_data = '''
    R0lGODdhyABkAKIAAAAAAP8mAP/7AP///wAAAAAAAAAAAAAAACH5BAkAAAQALAA
    AAADIAGQAAAP/KLrc/jDKSau9OOvNu/9gKI5kaZ5oqq5s675wLM90bd94ru987/
    /AoHBILBqPyKRyyWw6n9CodEqtWq/YrHbL7Xq/4LB4TC6bz+i0es1uu9/wuHxOl
    wTu+Lx+z+8H6jZ+goOEg4AnhYmKi3yHHIyQkZGOE5KWl5CUCpicnYx1nqGihHCj
    pqd+a6irrHlnrbCwY7G0sl+1uKxeubyoXL3AplnBxMJWxciex8nMmFXN0JJU0dS
    ZUtXYiVPZ3ILb3eB63+Hk4+Tg5ufc6erY0+3Zz/Du8vPQV/bRw/nFv/zAu/7lAi
    Ow1qyCq14hFKVqobM3Dj/RiUhKE0U8miIUzIihNh3HEPo+toglsqTJkyhTqlzJs
    qXLlzBjypxJs6bNmzhz6tzJs6fPn0CDCh1KtKjRo0iTKlWZAAA7
'''

root = tk.Tk()
image = tk.PhotoImage(data=image_data)
label = tk.Button(root, image=image, text="Hello, world", compound="center")
label.pack(padx=20, pady=20)

root.mainloop()

Upvotes: 1

Related Questions