欢迎访问宙启技术站
智能推送

使用Python的curses库实现终端日历应用

发布时间:2024-01-03 20:00:25

Curses库是Python中一个非常强大的终端UI库,它可以用来创建命令行界面应用程序。使用Curses库,我们可以在终端中创建各种交互式界面,包括日历应用。

下面是一个使用Curses库实现终端日历应用的例子:

import curses
import calendar

def draw_calendar(stdscr, year, month):
    # 获取当前月份的日历字符串
    cal = calendar.monthcalendar(year, month)
    
    # 获取终端的行数和列数
    rows, cols = stdscr.getmaxyx()
    
    # 计算日历的起始行和列
    start_row = (rows - len(cal)) // 2
    start_col = (cols - 21) // 2
    
    # 绘制日历界面
    stdscr.clear()
    stdscr.addstr(start_row - 2, start_col + 7, str(year) + "年" + str(month) + "月", curses.A_BOLD)
    stdscr.addstr(start_row, start_col, "日 一 二 三 四 五 六", curses.A_BOLD)
    
    for i, week in enumerate(cal):
        for j, day in enumerate(week):
            # 如果这一天是当前的日期,使用特殊的样式
            if day == 0:
                continue
            elif day == calendar.today().day and month == calendar.today().month and year == calendar.today().year:
                stdscr.addstr(start_row + i + 1, start_col + j * 3, str(day), curses.A_REVERSE)
            else:
                stdscr.addstr(start_row + i + 1, start_col + j * 3, str(day))
    
    stdscr.refresh()

def main(stdscr):
    # 初始年和月份
    year = calendar.today().year
    month = calendar.today().month
    
    # 隐藏光标
    curses.curs_set(0)
    
    # 绘制初始日历
    draw_calendar(stdscr, year, month)
    
    while True:
        # 等待用户输入
        key = stdscr.getch()
        
        # 上下左右按键切换月份
        if key == curses.KEY_UP:
            month -= 1
            if month < 1:
                month = 12
                year -= 1
        elif key == curses.KEY_DOWN:
            month += 1
            if month > 12:
                month = 1
                year += 1
        elif key == curses.KEY_LEFT:
            year -= 1
        elif key == curses.KEY_RIGHT:
            year += 1
        # q键退出程序
        elif key == ord('q'):
            break
        
        # 绘制新的日历
        draw_calendar(stdscr, year, month)

# 运行日历应用
curses.wrapper(main)

上面的代码首先导入了cursescalendar模块。然后定义了一个draw_calendar函数,用于绘制日历界面。

draw_calendar函数中,首先调用calendar.monthcalendar函数获取指定年份和月份的日历字符串。然后使用stdscr.getmaxyx函数获取终端的行数和列数,计算出日历的起始行和列。

在绘制界面时,先使用stdscr.clear函数清除之前的内容,然后使用stdscr.addstr函数在终端上绘制文本。其中,第一个参数为行索引,第二个参数为列索引,第三个参数为要显示的文本内容。curses.A_BOLD表示使用粗体样式,curses.A_REVERSE表示使用反转样式。

最后,在main函数中,先设置了终端的光标不可见,然后循环监听用户的按键输入,上下左右键可以切换月份,q键可以退出程序,其他按键不做处理。每次按键处理完后,调用draw_calendar函数绘制新的日历界面。

最后,使用curses.wrapper函数运行main函数,这样可以自动处理Curses模块的相关设置和恢复。 运行代码后即可在终端中看到一个日历界面,通过上下左右箭头键可以切换月份,按下q键退出程序。