pythontkintertkinter-label

Unable to set Label's background with TKinter


I am trying to use the "background" attribute to make the background of this label light gray, but it is leaving it as white (no errors given). The odd thing is if I set the "foreground" attribute, it changes the foreground correctly. Image of problem


from PIL import Image
import tkinter as tk
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter import font
from PIL import ImageTk, Image
from tkinter.ttk import *

window = tk.Tk()
window.title("PDF to JPG")
window.geometry("300x300")
window.configure(bg="#d1d1d1")

frame = tk.Frame(master=window, bg="#d1d1d1")
frame.pack(side=tk.BOTTOM, pady=50)
frame2 = tk.Frame(master=window, bg="#d1d1d1")
frame2.pack(side=tk.TOP, pady=50)

img_label = Label(master=frame2, text=f"Selected pdf: None", font=('Helvetica', 32), background="#d1d1d1")
img_label.grid(row=0, column=1, padx=5, pady=5)

On online guides, they say to use bg instead of the background attribute, but that gives me an error that bg is invalid. Using background does not give me an error, but it does not work as expected. (See image above)


Solution

  • Since you have the line from tkinter.ttk import * as the last import statement, so Label will be from ttk module. ttk.Label does not support bg option.

    It seems like your platform is MacOS and some widget styles cannot be changed in this platform.

    So use tk.Label instead of ttk.Label if you want to change the background color.

    Note that wildcard import is not recommended.