How do I get the background color of a Tkinter Canvas widget?


Tkinter canvas widget is used for many different purposes such as adding objects, drawing shapes, images and complex visuals to a graphical interface in an application. We can also configure its style such as background color, foreground color, and other properties using the configure properties or passing attributes.

Suppose we want to inherit the background color of the Canvas widget in another widget or in some part of the application. This can be achieved by using my_canvas["background"] property. Further, we can use canvas["background"] to fetch the background color of the canvas widget.

Example

# Import the required library
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame
win = Tk()
win.geometry("700x350")

# Add a Canvas widget
canvas = Canvas(win, background= "white")

# Draw a rectangle in Canvas and inherit the background color of Canvas
canvas.create_rectangle(50,50,350,190, outline="black", fill= canvas["background"])
canvas.pack()
win.mainloop()

Output

Executing the above code will display a window with a rectangle having the same background color as the canvas.

Updated on: 08-Jun-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements