Python Programming: Fonts and Colors in TKinter at V.H.N.S.N.College (Autonomous)

Posted by


TKinter is a widely-used Python library for building graphical user interfaces (GUIs). In this tutorial, we will specifically focus on working with fonts and colors in TKinter.

Font in TKinter:
By default, TKinter uses the system font for displaying text on widgets like labels, buttons, and entry fields. However, you can customize the font by specifying the font family, size, weight, and style.

To set the font for a widget, you can use the font parameter when creating the widget. Here’s an example of how to set the font for a label in TKinter:

import tkinter as tk

root = tk.Tk()

label = tk.Label(root, text="Hello, World!", font=("Arial", 12, "bold"))
label.pack()

root.mainloop()

In the above code, we create a label widget with the text "Hello, World!" and set the font to Arial, size 12, and bold weight.

You can also set the font using the config method:

label.config(font=("Times New Roman", 14, "italic"))

Colors in TKinter:
TKinter supports a wide range of colors that you can use to customize the appearance of your GUI. You can specify colors using color names, RGB values, or hexadecimal values.

To set the background color of a widget, you can use the bg parameter when creating the widget:

button = tk.Button(root, text="Click me", bg="red")

You can also set the foreground (text) color using the fg parameter:

label = tk.Label(root, text="Hello, World!", fg="blue")

To set colors using RGB values, you can use a tuple with three integers representing the red, green, and blue components of the color:

label.config(bg=(255, 0, 0))  # Red background color

You can also use hexadecimal values to specify colors:

button.config(bg="#00FF00")  # Green background color

Combining Fonts and Colors:
You can combine font and color customization to create visually appealing GUIs. Here’s an example that demonstrates setting both font and color for a label widget:

label = tk.Label(root, text="Hello, World!", font=("Helvetica", 16, "italic"), fg="purple", bg="yellow")

In this example, we set the font to Helvetica, size 16, italic style, and a purple foreground color with a yellow background color.

Overall, customizing fonts and colors in TKinter can help you create polished and professional-looking GUIs for your Python applications. Experiment with different font families, sizes, weights, styles, and colors to find the combination that best suits your project.

I hope this tutorial was helpful in understanding how to work with fonts and colors in TKinter. Feel free to explore further customization options and experiment with different styles to create unique and visually appealing GUIs.