【问题标题】:Python using tkcalendar with if-statementsPython 使用带有 if 语句的 tkcalendar
【发布时间】:2020-11-26 09:48:47
【问题描述】:

我正在尝试使用 tkcalendar 进行 if 语句,但不知道为什么它不起作用。

from tkinter import *
from tkcalendar import *
import datetime

root = Tk()
root.title('Hi')
root.geometry('500x400')

cal = Calendar(root, date_pattern="d/m/y", year = 2020, month = 11, day = 1)
cal.pack(pady=20)

def grab_date():
    my_label.config(text = cal.get_date())
    d = cal.get_date()
    print(d)
    if datetime.datetime.strptime('01/11/2020', "%d/%m/%Y").strftime("%d/%m/%Y") 
    <=d<=datetime.datetime.strptime('01/1/2021', "%d/%m/%Y").strftime("%d/%m/%Y"):
        print('ok')

my_button = Button(root, text = 'Get date', command = grab_date)
my_button.pack()

my_label = Label(root, text = ' ')
my_label.pack(pady = 20)

root.mainloop()

当我在日期之间按下按钮时,它不会打印“ok”。有谁知道我如何解决这个问题以及使用 tkcalendar 时如何完成 if 语句?然后我想添加更多条件,说明何时按下其他日期打印其他内容。

【问题讨论】:

  • 你想在 if 语句中检查什么?
  • @HarshaBiyani 看看如果我按下“2020 年 1 月 11 日”和“2021 年 1 月 1 日”之间的按钮,我希望程序打印:好的
  • cal.get_date() 是返回一个 datetime 对象还是需要先转换它?
  • @scotty3785 它返回一个日期时间对象,格式为:日/月/年
  • 好声@HarshaBiyani,Carl-Erik Pettersson 应该比较日期时间对象而不是字符串,因此将字符串转换为日期时间然后再转换回字符串是没有意义的。

标签: python python-3.x if-statement tkinter tkcalendar


【解决方案1】:

考虑下面的例子。

import datetime



def betweenDates(date,start,end):
    return (date>start) and (date<end)

start = datetime.datetime.strptime('01/11/2020', "%d/%m/%Y").date()
end = datetime.datetime.strptime('01/1/2021', "%d/%m/%Y").date()

today = datetime.datetime.now().date()

if betweenDates(today,start,end):
    print("Ok")

这将使用函数比较今天的日期以查看它是否在两个指定日期之间(使 if 语句行更短并且比较可重用)。

要使用 tkcalendar 执行此操作,您需要将日期从它转换为 datetime 对象(或者因为您要删除时间,所以需要一个 datetime.date 对象)

由于 tkcalendar 返回一个字符串,您需要使用 strptime 来解析它。可能是这样的

d = datetime.datetime.strptime(cal.get_date(),"%d/%m/%Y").date()

希望能帮助你的代码正常工作

编辑:您的函数可能如下所示。但是由于未安装 tkcalendar 而未经测试

def grab_date():
    my_label.config(text = cal.get_date())
    d = datetime.datetime.strptime(cal.get_date(),"%d/%m/%Y").date()
    print(d)
    start = datetime.datetime.strptime('01/11/2020', "%d/%m/%Y").date()
    end = datetime.datetime.strptime('01/1/2021', "%d/%m/%Y").date()
    if betweenDates(d,start,end):
        print('ok')

【讨论】:

  • 谢谢先生!我会试试这个!你的意思是我应该输入: if betweenDates(d,start,end): print("Ok") where d = datetime.datetime.strptime(cal.get_date(),"%d/%m/%Y") .date()
  • 或者我也应该对 start、end 做点什么?
  • @Carl-ErikPettersson 不。我已经编辑了我的问题以显示它的外观。您还可以考虑更改 betweenDates 以进行从字符串到 datetime.date() 对象的转换
  • 你说得对:TypeError: can't compare datetime.datetime to datetime.date。我应该对 betweenDates 函数进行一些更改。我这样返回:return (date.datetime.date()>start.datetime.date()) 和 (date.datetime.date()
  • 我的错误。将.date() 添加到以d = 开头的行的末尾。那么所有dstartend 都将是datetime.date 对象并且可比较
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-16
  • 2018-01-07
  • 2018-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-30
相关资源
最近更新 更多