Tkinter is a popular Python module for creating graphical user interfaces (GUIs). It comes bundled with Python, making it a go-to choice for developing GUI applications.
Entry widgets allow users to input text. You can create an entry widget with the following syntax:
entry = ttk.Entry(master, option=value, ...)
Example Code #1: Creating an Entry widget to capture user input (accepting only string data).
# importing tkinter
from tkinter import *
from tkinter import ttk
from tkinter.messagebox import askyesno
# creating root
root = Tk()
root.geometry('200x100')
input_text = StringVar()
# This class is used to add styling
# to any widget which are available
style = ttk.Style()
style.configure('TEntry', foreground = 'red')
entry1 = ttk.Entry(root, textvariable = input_text, justify = CENTER,
font = ('courier', 15, 'bold'))
entry1.focus_force()
entry1.pack(side = TOP, ipadx = 30, ipady = 10)
save = ttk.Button(root, text = 'Save', command = lambda : askyesno(
'Confirm', 'Do you want to save?'))
save.pack(side = TOP, pady = 10)
root.mainloop()
Output:


Explanation of the above code:
Importing Tkinter modules:
from tkinter import *: Imports all the necessary Tkinter components for GUI creation.from tkinter import ttk: Importsttk, which provides theming and additional widget support.from tkinter.messagebox import askyesno: Imports theaskyesnofunction to display a confirmation dialog box.
Creating the root window:
root = Tk(): Initializes the main window (or root window) of the GUI application.root.geometry('200x100'): Sets the size of the window to 200 pixels wide and 100 pixels high.
Defining input text variable:
input_text = StringVar(): Creates a TkinterStringVarobject to hold the text input from theEntrywidget.
Configuring styles with ttk.Style:
style = ttk.Style(): Initializes theStyleclass fromttkto customize widget styles.style.configure('TEntry', foreground='red'): Configures theTEntrywidget style to set the text color (foreground) to red.
Creating the Entry widget:
entry1 = ttk.Entry(...): Creates an input field usingttk.Entrywidget.textvariable=input_text: Binds the input field toinput_text, storing the user’s input.justify=CENTER: Aligns the entered text to the center of theEntrywidget.font=('courier', 15, 'bold'): Sets the font of the input text to Courier, size 15, and bold style.entry1.focus_force(): Automatically focuses the cursor on theEntrywidget when the window loads.entry1.pack(side=TOP, ipadx=30, ipady=10): Positions theEntrywidget at the top, with internal padding (ipadxandipady).
Creating the ‘Save’ button:
save = ttk.Button(...): Creates a button labeled “Save”.command=lambda: askyesno('Confirm', 'Do you want to save?'): Attaches a command to the button that opens a confirmation dialog box asking if the user wants to save when clicked.save.pack(side=TOP, pady=10): Places the button just below theEntrywidget with padding of 10 pixels on the vertical axis.
Running the Tkinter main loop:
root.mainloop(): Starts the Tkinter event loop, which keeps the application running and responsive to user interactions.
Let us check an enhanced version
# Importing tkinter
from tkinter import *
from tkinter import ttk
from tkinter.messagebox import askyesno, showinfo
# Creating root window
root = Tk()
root.title("Creative Input Box") # Added a title for the window
root.geometry('300x150') # Increased the window size for better layout
# Setting a background color for the root window
root.configure(bg='#f0f0f0')
input_text = StringVar()
# Customizing style for Entry and Button widgets
style = ttk.Style()
style.configure('TEntry', foreground='blue', background='#e0f7fa', fieldbackground='#f7fff7')
style.configure('TButton', foreground='blue', background='#e0f7fa', font=('Helvetica', 12, 'bold'))
# Creating a label for better UX
label = ttk.Label(root, text="Enter your name:", font=('Arial', 12), background='#f0f0f0')
label.pack(side=TOP, pady=5)
# Creating the Entry widget with customized style
entry1 = ttk.Entry(root, textvariable=input_text, justify=CENTER, font=('courier', 15, 'italic'))
entry1.focus_force()
entry1.pack(side=TOP, ipadx=30, ipady=10)
# Function to handle 'Save' action with added features
def save_action():
user_input = input_text.get()
if user_input:
response = askyesno('Confirm', f"Do you want to save '{user_input}'?")
if response:
showinfo("Saved", f"Your input '{user_input}' has been saved successfully!")
else:
showinfo("Cancelled", "Your input was not saved.")
else:
showinfo("No Input", "Please enter something before saving.")
# Creating a styled 'Save' button with additional action
save = ttk.Button(root, text='Save', command=save_action)
save.pack(side=TOP, pady=10)
# Creating a 'Clear' button for user convenience
def clear_input():
input_text.set('') # Clears the text in the Entry widget
entry1.focus_force()
clear_button = ttk.Button(root, text='Clear', command=clear_input)
clear_button.pack(side=TOP, pady=5)
# Starting the main event loop
root.mainloop()
Output:



In this article, we explored how to add style to input text using the ttk.Entry widget in Tkinter. Tkinter, being one of the most widely-used libraries for Python GUI development, provides basic widgets for user input, but with the inclusion of ttk (Themed Tkinter), it offers more modern and polished widgets. One of the key components in creating user-friendly applications is enhancing the visual aesthetics and interactivity of input fields, which is where styling comes into play.
We began by understanding the importance of Entry widgets in capturing user inputs in a GUI. While the default Entry widget is functional, customizing it using the ttk.Style class allows developers to tailor the look and feel of the input fields to fit the theme and design of their application. By configuring parameters such as text color, background color, font size, and alignment, you can significantly improve the visual appeal of the input fields.
Additionally, we demonstrated how to change the text’s appearance in the ttk.Entry widget by adjusting the foreground color, font style, and alignment. This customization is particularly useful for applications that need to differentiate between different types of inputs, provide visual cues, or simply enhance the overall user experience.
Beyond aesthetics, these enhancements also have practical benefits. For instance, aligning text and changing font sizes can improve readability, which is crucial for data entry forms, calculators, or any application where users frequently interact with input fields. Consistent and well-designed input fields create a better user experience, making the application more intuitive and easier to navigate.
By adding custom styles, such as coloring the text red or green to indicate errors or valid inputs, developers can create more interactive and responsive applications. Furthermore, the integration of buttons alongside the Entry widget, as demonstrated with the “Save” button, shows how you can combine input fields with action-based widgets to make your GUI more functional and dynamic.
In summary, the ability to style ttk.Entry widgets in Tkinter gives developers the flexibility to create visually appealing and user-friendly applications. This customization not only improves aesthetics but also enhances functionality by guiding user input and improving interaction. By leveraging the ttk.Style class, you can easily adapt the appearance of your widgets to fit the theme of your application, whether you’re building a small desktop tool or a larger, more complex GUI. With these tools in hand, you’re well-equipped to make your Tkinter applications both functional and visually engaging.





Leave a Reply