- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to change the color of a Tkinter rectangle on clicking?
The Canvas widget is one of the most versatile widgets in the Tkinter Library. It is used for creating shapes of different types and sizes, animating objects, visualizing graphics, and many more. To change the property of a particular item in Tkinter, we can use itemconfig(**options) method. It takes options such as background color, outline color, and other useful properties of the items defined in a canvas.
In this example, we will create a rectangle such that the color inside the rectangle would change after clicking a Button.
# Import the required libraries from tkinter import * from tkinter import ttk # Create an instance of Tkinter Frame win = Tk() # Set the geometry win.geometry("700x300") # Define a function to change the state of the Widget def change_color(): canvas.itemconfig(rectangle, fill='green') # Define a Canvas Widget canvas = Canvas(win, width=500, height=240) canvas.pack() # Create a rectangle in Canvas rectangle = canvas.create_rectangle(100, 100, 400, 400, fill='blue') # Create a Button to Disable the Combobox Widget ttk.Button(win, text="Change Color", command=change_color).pack() win.mainloop()
When you run the above code, it will display a window with a blue-colored rectangle at the center.
Now, click the "Change Color" button. It will change the color of the rectangle to green.
- Changing the color a Tkinter rectangle on clicking
- How to change the color of a Tkinter label programmatically?
- How to fully change the color of a Tkinter Listbox?
- How to change the background color of a Treeview in Tkinter?
- How to change the background color of a tkinter Canvas dynamically?
- How to change the color of ttk button in Tkinter?
- How to change the mouse pointer color in Tkinter?
- How to change the color of certain words in a Tkinter text widget?
- How to change text cursor color in Tkinter?
- How to colorize the outline of a Tkinter canvas rectangle?
- How to change the size of text on a label in Tkinter?
- How to make a Button Hover to change the Background Color in Tkinter?
- How to change the background color of ListView items on Android?
- How to change the menu background color of Tkinter's OptionMenu widget?
- Dynamically change the widget background color in Tkinter