,

Python Tkinter Library is Awsome !

Python Tkinter Library is Awsome !

Python’s tkinter library provides a simple way to create graphical user interfaces (GUIs) for desktop applications. In this tutorial, we will create a basic calendar application using tkinter. The calendar will display the current month with the ability to navigate to previous and next months. Additionally, we will add a feature to select a date and display it in a label.

Prerequisites: Before we start, make sure you have Python installed on your system. You will also need to have the tkinter library installed, which is included in the standard Python distribution.

Code:

import calendar
import tkinter as tk

def show_calendar():
# Get the year and month from the entry widgets
year = int(year_entry.get())
month_name = month_entry.get().capitalize()

# Mapping of month names to their corresponding numeric values
month_mapping = {
'January': 1, 'February': 2, 'March': 3, 'April': 4, 'May': 5, 'June': 6,
'July': 7, 'August': 8, 'September': 9, 'October': 10, 'November': 11, 'December': 12
}

# Check if the month name is valid
if month_name not in month_mapping:
print('Invalid month name')
return

month = month_mapping[month_name]

# Clear any previous calendar display
calendar_text.delete('1.0', tk.END)

# Display the calendar for the specified year and month
cal = calendar.month(year, month)
calendar_text.insert(tk.INSERT, cal)

# Create the main window
root = tk.Tk()
root.title('Calendar GUI')

# Create input fields for year and month
year_label = tk.Label(root, text='Year:')
year_label.pack()
year_entry = tk.Entry(root)
year_entry.pack()

month_label = tk.Label(root, text='Month:')
month_label.pack()
month_entry = tk.Entry(root)
month_entry.pack()

# Create a button to show the calendar
show_button = tk.Button(root, text='Show Calendar', command=show_calendar)
show_button.pack()

# Create a text widget to display the calendar
calendar_text = tk.Text(root, height=10, width=25)
calendar_text.pack()

# Start the tkinter event loop
root.mainloop()

Output:

Explanation of the whole code:

def show_calendar():

This line defines a function called show_calendar that will be called when the “Show Calendar” button is clicked.

    year = int(year_entry.get())
month_name = month_entry.get().capitalize()

These lines retrieve the values entered in the year_entry and month_entry widgets. The int function is used to convert the year value to an integer. capitalize() is used to ensure that the month name is in title case (e.g., “March” instead of “march”).

    month_mapping = {
'January': 1, 'February': 2, 'March': 3, 'April': 4, 'May': 5, 'June': 6,
'July': 7, 'August': 8, 'September': 9, 'October': 10, 'November': 11, 'December': 12
}

This dictionary maps month names to their corresponding numeric values. It will be used to convert the month name to an integer.

    if month_name not in month_mapping:
print('Invalid month name')
return

This if statement checks if the entered month name is in the month_mapping. If it’s not, it prints an error message and returns from the function early.

    month = month_mapping[month_name]

If the month name is valid, this line retrieves the corresponding numeric value from month_mapping.

    calendar_text.delete('1.0', tk.END)

This line clears any previous calendar display in the calendar_text widget. delete('1.0', tk.END) deletes all text from the widget starting from the first character ('1.0') to the end.

    cal = calendar.month(year, month)

This line generates a calendar for the specified year and month using the calendar.month function. The result is a string containing the formatted calendar for that month and year.

    calendar_text.insert(tk.INSERT, cal)

Finally, this line inserts the generated calendar string (cal) into the calendar_text widget at the current insertion point (tk.INSERT), which is typically at the beginning of the widget.

In this tutorial, we have learned how to create a simple calendar application using Python’s tkinter library. We have created a basic GUI that allows the user to input a year and month and then displays the corresponding calendar. You can further enhance this application by adding features such as event handling and customizing the appearance of the calendar.

To enhance the calendar application, we can add event handling for selecting dates and customize the appearance of the calendar. Here’s an updated version of the show_calendar function with these features

def show_calendar():
# Get the year and month from the entry widgets
year = int(year_entry.get())
month_name = month_entry.get().capitalize()

# Mapping of month names to their corresponding numeric values
month_mapping = {
'January': 1, 'February': 2, 'March': 3, 'April': 4, 'May': 5, 'June': 6,
'July': 7, 'August': 8, 'September': 9, 'October': 10, 'November': 11, 'December': 12
}

# Check if the month name is valid
if month_name not in month_mapping:
print('Invalid month name')
return

month = month_mapping[month_name]

# Clear any previous calendar display
calendar_text.delete('1.0', tk.END)

# Display the calendar for the specified year and month
cal = calendar.month(year, month)
calendar_text.insert(tk.INSERT, cal)

# Bind events for selecting dates
def on_date_click(event):
date = calendar_text.tag_names(tk.CURRENT)[0]
print(f'Selected date: {date}')

calendar_text.tag_configure('date', foreground='blue', underline=True)
calendar_text.tag_bind('date', '<Button-1>', on_date_click)

# Customize the appearance of the calendar
for line in cal.split('\n')[2:]:
for i in range(7):
date_str = line[i * 3:i * 3 + 2].strip()
if date_str:
start = f'{line[:i * 3 + 2]}1.{line[i * 3 + 2:].find(date_str) + 2}'
end = f'{start}+2c'
calendar_text.tag_add(date_str, start, end)
calendar_text.tag_config(date_str, background='lightyellow', foreground='black')

calendar_text.configure(state='disabled')

Explanation of show calendar:

def show_calendar():
year = int(year_entry.get())
month_name = month_entry.get().capitalize()

month_mapping = {
'January': 1, 'February': 2, 'March': 3, 'April': 4, 'May': 5, 'June': 6,
'July': 7, 'August': 8, 'September': 9, 'October': 10, 'November': 11, 'December': 12
}

if month_name not in month_mapping:
print('Invalid month name')
return

month = month_mapping[month_name]
  • year = int(year_entry.get()): Retrieves the year entered in the year entry widget and converts it to an integer.
  • month_name = month_entry.get().capitalize(): Retrieves the month name entered in the month entry widget and capitalizes it.
  • month_mapping: Maps month names to their corresponding numeric values.
  • if month_name not in month_mapping: Checks if the entered month name is valid.
  • month = month_mapping[month_name]: Retrieves the numeric value of the entered month name from the mapping.
    calendar_text.delete('1.0', tk.END)

cal = calendar.month(year, month)
calendar_text.insert(tk.INSERT, cal)
  • calendar_text.delete('1.0', tk.END): Clears any previous calendar display in the text widget.
  • cal = calendar.month(year, month): Generates a calendar for the specified year and month.
  • calendar_text.insert(tk.INSERT, cal): Inserts the generated calendar into the text widget.
    def on_date_click(event):
date = calendar_text.tag_names(tk.CURRENT)[0]
print(f'Selected date: {date}')

calendar_text.tag_configure('date', foreground='blue', underline=True)
calendar_text.tag_bind('date', '<Button-1>', on_date_click)
  • on_date_click: Defines a callback function to handle date selection events.
  • calendar_text.tag_configure('date', foreground='blue', underline=True): Configures a tag for date highlighting.
  • calendar_text.tag_bind('date', '<Button-1>', on_date_click): Binds the on_date_click function to the date tag for handling click events.
    for line in cal.split('\n')[2:]:
for i in range(7):
date_str = line[i * 3:i * 3 + 2].strip()
if date_str:
start = f'{line[:i * 3 + 2]}1.{line[i * 3 + 2:].find(date_str) + 2}'
end = f'{start}+2c'
calendar_text.tag_add(date_str, start, end)
calendar_text.tag_config(date_str, background='lightyellow', foreground='black')

calendar_text.configure(state='disabled')
  • This block of code iterates over the lines of the calendar text and processes each date to highlight it.
  • It uses tags to apply background and foreground colors to highlight the date.
  • Finally, it disables the text widget to prevent editing of the calendar display.

Happy Coding!

Don’t forget to Subscribe for more!

Author

Sona Avatar

Written by

One response to “Python Tkinter Library is Awsome !”

  1. […] tkinter import *: This line imports everything (*) from the tkinter module, which is used to create graphical user interfaces […]

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>