Prerequisites: Tkinter GUI, Tkinter Widgets
Tkinter is Python’s standard GUI package which provides us with a variety of common GUI elements such as buttons, menus, and various kinds of entry fields and display areas which we can use to build out an interface. These elements are called Tkinter Widgets.
Among all color options for a widget, there is no direct method to change the border color of the widget. As the border color of a widget is tied to the background color of the widget, it is impossible to set it individually. But, we do have some methods to color the border of a widget and those methods are discussed below.
Method 1: Using Frame widget
Instead of using the default border of a widget, we can use the Frame widget as an alternative border, where we can set the background color of the Frame widget to any color we want. This method works with every widget.
- Import Tkinter module
- Create a window
- Create a border variable with Frame widget with background color as its attributes
- Create any widget with the border variable as an attribute
- Place the widget on the window created
Example:
Python3
# import tkinter from tkinter import * # Create Tk object window = Tk() # Set the window title window.title( 'GFG' ) # Create a Frame for border border_color = Frame(window, background = "red" ) # Label Widget inside the Frame label = Label(border_color, text = "This is a Label widget" , bd = 0 ) # Place the widgets with border Frame label.pack(padx = 1 , pady = 1 ) border_color.pack(padx = 40 , pady = 40 ) window.mainloop() |
Output:
Method 2: Using highlightbackground and highlightcolor
We can also use a highlighted background and highlight color together to get a border color for our widget. We can even adjust the thickness of the border using the highlight thickness attribute. This method only works for some widgets like Entry, Scale, Text e.t.c.
- Import Tkinter module
- Create a window
- Create a widget with highlightthickness set to desired border thickness
- Configure highlightbackground and highlightcolor attributes to the desired border-color
- Place the widget on the window created
Example:
Python3
# import tkinter from tkinter import * # Create Tk object window = Tk() # Set the window title window.title( 'GFG' ) # Entry Widget # highlightthickness for thickness of the border entry = Entry(highlightthickness = 2 ) # highlightbackground and highlightcolor for the border color entry.config(highlightbackground = "red" , highlightcolor = "red" ) # Place the widgets in window entry.pack(padx = 20 , pady = 20 ) window.mainloop() |
Output:
Note: It is recommended to use Method 1 for setting the border color of a widget as Method 2 may or may not work for some widgets. But Method 1 works universally on any widget.