You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python计算tkcalendar选中日期与当前日期天数差及VS Code导包报错解决

解决方法

1. 选中日期与当前日期差计算

tkcalendar的DateEntry.get_date()方法返回的是标准datetime.date类型对象,直接和当前日期做减法即可得到相差天数,修改后的完整可运行代码如下:

from tkinter import *
from tkinter import messagebox
import datetime
from tkcalendar import *

root = Tk()
root.title("日期差计算")
root.resizable(False, False)
root.geometry("200x200+600+100")

def days():
    # 获取选中日期
    selected_date = txt_pdate.get_date()
    # 获取当前本地日期
    current_date = datetime.date.today()
    # 计算天数差,abs保证结果为正
    diff_days = abs((selected_date - current_date).days)
    # 弹出结果提示
    messagebox.showinfo("计算结果", f"选中日期与当前日期相差{diff_days}天")

Label(root, text= '选择日期 :').pack()
txt_pdate = DateEntry(root)
txt_pdate.pack()

btn = Button(root, text='计算天数差', command= days).pack()

root.mainloop()

2. VS Code提示report missing import错误解决

这个是VS Code默认Pylance语法检查插件的路径识别问题,和代码实际运行无关,按以下步骤处理即可:

  • 点击VS Code右下角的Python解释器版本,选择你实际安装了tkcalendar的对应环境(使用虚拟环境的话需要选到虚拟环境下的Python解释器)
  • 如果选择正确后仍有报错,在导入tkcalendar的行末尾加上注释# type: ignore,即可屏蔽该提示

内容的提问来源于stack exchange,提问作者SudipRaaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 18:27:04