Python Tkinter Tk Calendar 获取自定义日期无效且无法以以下格式显示日期:"DD-MM-YYYY"
Python Tkinter Tk Calendar get custom date not working and unable to display date in format: "DD-MM-YYYY"
我想创建一个日期选择器,但它根本不起作用,无论我在以下菜单中选择什么日期:
它只输出当前日期:
第二次我点击调用函数的按钮dispcal()
,IDLE自动打印出当前日期,我不知道为什么。当我单击按钮 Get This Date 并调用函数 getCustomDate()
时,它只是没有执行它应该执行的操作,也没有打印任何内容。
这里是日期选择器和日历函数的代码:
def getCustomDate():
print(cal.get_date())
def dispcal():
global cal
calFrame=LabelFrame(mainL,borderwidth=0, bg="#c3dde6", height=100, width=100)
calFrame.grid(row=1, column=0, sticky=NSEW)
cal=Calendar(calFrame, selectmode="day",firstweekday="monday",background="#0f8bff",foreground="black",disabledforeground="#a3bec7",bordercolor="grey",normalbackground="#d0f4ff",weekendbackground="#8ffeff",weekendforeground ="black" ,disabledbackground="99b3bc",year=int(datetime.datetime.now().strftime("%Y")),month=int(datetime.datetime.now().strftime("%m")), day=int(datetime.datetime.now().strftime("%d")))
cal.pack(pady=10)
getdat=Button(calFrame,text="Get This Date",bg="#00ffde", command=getCustomDate())
getdat.pack()
更新
感谢@j_4321 解决了我的问题,我创建了一个新的 python 文件和其中的代码 运行,我想要的自定义格式的日历日期选择器,它就像一个魅力,并提供所需的输出。
fresh.py:
from tkinter import *
from tkcalendar import *
root=Tk()
root.geometry("500x500")
def mainF():
global cal
def getDate():
date=cal.get_date()
print(date)
cal.pack(pady=20, padx=20)
butt=Button(root,text="Date Getter", bg="cyan",command=getDate).pack()
cal=Calendar(root,selectmode="day",date_pattern="dd-mm-y")
but=Button(root,text="Pick Date",command=mainF).pack()
root.mainloop()
但是在我的 main.py 中,相同的代码不起作用并给出以下错误消息:
<bound method Calendar.get_date of <tkcalendar.calendar_.Calendar object .!labelframe.!frame2.!frame.!frame2.!calendar>>
我不知道为什么会这样,也许我的 main.py 代码有问题,但我似乎无法找到它。
这是我的main.py代码:
from calendar import firstweekday
import csv, datetime
from tkinter import *
from tkcalendar import *
from tkinter import ttk
from PIL import Image, ImageTk
now=datetime.datetime.now().strftime("%d-%m-%Y")
f=open("Dr Nikhil Prescription App\Patient_Data.csv","r", newline="")
reader=csv.reader(f, delimiter=",")
L=[k[0] for k in reader]
try:
sndat=str(1+(int(L[-1])))
except ValueError:
sndat=1
f.close()
from tkinter import messagebox
def DataAdder2CSV():
global edate, eSNO, eage, egender, ename, ePID, econtact, ecomp, eallergy, ehistory, eR
e=edate.get()
a=eSNO.get()
d=eage.get()
f=egender.get()
b=ename.get()
c=ePID.get()
g=econtact.get()
h=ecomp.get(1.0,END)
i=eallergy.get(1.0,END)
j=ehistory.get(1.0,END)
k=eR.get(1.0,END)
data=[a,b,c,d,e,f,g,h,i,j,k]
file=open("Patient_Data.csv","a", newline="")
writer=csv.writer(file, delimiter=",")
writer.writerow(data)
file.close()
messagebox.showinfo("Prescription Generator", "Data has been saved to the database successfully!")
def PrescGen():
from tkinter import filedialog
root.filename=filedialog.askdirectory(initialdir="Documents", title="Choose Destination Folder")
'''
import win32com.client, os
psApp = win32com.client.Dispatch("Photoshop.Application")
psApp.Open("Presc_Template.psd")
doc = psApp.Application.ActiveDocument
layer_facts = doc.ArtLayers["GLAYER"]
text_of_layer = layer_facts.TextItem
text_of_layer.contents = "This is an example of a new text."
'''
messagebox.showinfo("Prescription Generator", "Prescription has been saved in the desired location successfully!")
def dispcal():
calFrame.grid(row=1, column=0,pady=60, sticky=NSEW)
cal.pack(pady=10,padx=50, fill="both", expand=True)
def getCustomDate():
print(cal.get_date)
getdat=Button(calFrame,text="Get This Date",bg="#00ffde", command=getCustomDate)
getdat.pack()
root=Tk()
root.config(bg="#add8e6")
megaF=LabelFrame(root,bg="#add8e6", borderwidth=0)
megaF.pack()
greet=Label(megaF,font="Arial 25",text="Prescription Generator", bg="#add8e6", fg="black").pack(pady=20)
dateF=Frame(megaF, padx=10, pady=10, bg="#c3dde6")
dateF.pack()
mega2F=Frame(megaF,bg="#c3dde6")
mega2F.pack()
date=Label(dateF,font="Arial 12",text="Date:", bg="#c3dde6").grid(row=0,column=0)
edate=Entry(dateF, width=10)
edate.insert(0,now)
edate.grid(row=0, column=1, padx=5)
CalIMG=ImageTk.PhotoImage(Image.open("D:\Coding\Python Scripts\Dr Nikhil Prescription App\cal.png"))
mainL=Frame(mega2F,borderwidth=0, padx=10, pady=10, bg="#c3dde6")
mainL.grid(row=0, column=0)
calFrame=Frame(mainL,borderwidth=0, bg="#c3dde6", height=200, width=100)
cal=Calendar(calFrame,
date_pattern="dd-mm-y",
selectmode="day",
firstweekday="monday",
background="#0f8bff",
foreground="black",
disabledforeground="#a3bec7",
bordercolor="grey",
normalbackground="#d0f4ff",
weekendbackground="#8ffeff",
weekendforeground ="black" ,
disabledbackground="99b3bc")
CalButt=Button(dateF, image=CalIMG, command=dispcal, borderwidth=0, bg="#c3dde6").grid(row=0, column=2, padx=5)
main2L=LabelFrame(mega2F,borderwidth=0, padx=10, pady=10, bg="#c3dde6")
main2L.grid(row=0, column=1,pady=20, padx=40)
PDlf=Frame(mainL, padx=10, pady=13, bg="#c3dde6")
PDlf.grid(row=0, column=0, sticky=NSEW)
sno=Label(PDlf,font="Arial 14",text="Sno:", bg="#c3dde6").grid(row=0,column=0, sticky=E)
eSNO=Entry(PDlf, width=3)
eSNO.insert(0,sndat)
eSNO.grid(row=0, column=1)
age=Label(PDlf,font="Arial 14",text="Age:", bg="#c3dde6").grid(row=1,column=0, sticky=E)
eage=Entry(PDlf, width=3)
eage.grid(row=1, column=1, pady=10)
gender=Label(PDlf,font="Arial 14",text="Gender:", bg="#c3dde6").grid(row=2,column=0, sticky=E)
egender=Entry(PDlf, width=3)
egender.grid(row=2, column=1)
name=Label(PDlf,font="Arial 14",text="Name:", bg="#c3dde6").grid(row=0,column=3, sticky=E)
ename=Entry(PDlf, width=15)
ename.grid(row=0, column=4)
Pid=Label(PDlf,font="Arial 14",text="PatientID:", bg="#c3dde6").grid(row=1,column=3, sticky=E)
ePID=Entry(PDlf, width=15)
ePID.grid(row=1, column=4, pady=10)
contact=Label(PDlf,font="Arial 14",text="Contact:", bg="#c3dde6").grid(row=2,column=3, sticky=E)
econtact=Entry(PDlf, width=15)
econtact.grid(row=2, column=4)
blank=Label(PDlf,font="Arial 14",text=" ", bg="#c3dde6").grid(row=1,column=2)
contentLF=LabelFrame(main2L, padx=10, pady=10, bg="#c3dde6", borderwidth=0)
contentLF.grid(row=0, column=2, sticky=SE)
blank=Label(PDlf,font="Arial 14",text=" ", bg="#c3dde6").grid(row=0,column=2)
complaint=Label(contentLF,font="Arial 14",text="Complaint:", bg="#c3dde6").grid(row=0,column=1, sticky=E)
ecomp=Text(contentLF, width=90, height=4)
ecomp.grid(row=0, column=2)
allergy=Label(contentLF,font="Arial 14",text="Allergy:", bg="#c3dde6").grid(row=1,column=1, sticky=E)
eallergy=Text(contentLF, width=90, height=2)
eallergy.grid(row=1, column=2, pady=10)
history=Label(contentLF,font="Arial 14",text="History:", bg="#c3dde6").grid(row=2,column=1, sticky=E)
ehistory=Text(contentLF, width=90, height=5)
ehistory.grid(row=2, column=2)
R=Label(contentLF,font="Arial 14",text="Diagnosis:", bg="#c3dde6").grid(row=3,column=1, sticky=E)
eR=Text(contentLF, width=90, height=12)
eR.grid(row=3, column=2, pady=10)
buttF=LabelFrame(main2L, bg="#c3dde6", borderwidth=0)
buttF.grid(row=4, column=2, sticky=E)
genPres=Button(buttF,font="Arial 12",text="Generate Prescription", bg="#ff80b9", command=PrescGen).grid(row=0, column=0, padx=10, sticky=E)
csvAdd=Button(buttF,font="Arial 12",text="Add to Database", bg="#49ff9a", command=DataAdder2CSV).grid(row=0, column=1,padx=10, sticky=E)
root.title("Prescription Generator")
root.state("zoomed")
root.mainloop()
首先,在
getdat=Button(calFrame,text="Get This Date",bg="#00ffde", command=getCustomDate())
您正在执行函数而不是将其作为参数传递,如 Why is the command bound to a Button or event executed when declared?.
然后,根据 Calendar 的文档字符串,它需要一个 date_pattern
选项
date_pattern : str
date pattern used to format the date as a string. The default
pattern used is babel's short date format in the Calendar's locale.
A valid pattern is a combination of 'y', 'm' and 'd' separated by
non letter characters to indicate how and in which order the
year, month and day should be displayed.
y: 'yy' for the last two digits of the year, any other number of 'y's for
the full year with an extra padding of zero if it has less
digits than the number of 'y's.
m: 'm' for the month number without padding, 'mm' for a
two-digit month
d: 'd' for the day of month number without padding, 'dd' for a
two-digit day
Examples for datetime.date(2019, 7, 1):
'y-mm-dd' → '2019-07-01'
'm/d/yy' → '7/1/19'
所以在创建日历时只需在参数中传递 date_pattern="dd-mm-yyyy"
。
这是一个例子
from tkinter import Tk, Button
from tkcalendar import Calendar
def getCustomDate():
print(cal.get_date())
root = Tk()
cal = Calendar(root,
selectmode="day",
firstweekday="monday",
background="#0f8bff",
foreground="black",
disabledforeground="#a3bec7",
bordercolor="grey",
normalbackground="#d0f4ff",
weekendbackground="#8ffeff",
weekendforeground ="black",
disabledbackground="99b3bc",
date_pattern="dd-mm-yyyy")
cal.pack(pady=10)
getdat=Button(root, text="Get This Date",
bg="#00ffde", command=getCustomDate)
getdat.pack()
root.mainloop()
我想创建一个日期选择器,但它根本不起作用,无论我在以下菜单中选择什么日期:
它只输出当前日期:
第二次我点击调用函数的按钮dispcal()
,IDLE自动打印出当前日期,我不知道为什么。当我单击按钮 Get This Date 并调用函数 getCustomDate()
时,它只是没有执行它应该执行的操作,也没有打印任何内容。
这里是日期选择器和日历函数的代码:
def getCustomDate():
print(cal.get_date())
def dispcal():
global cal
calFrame=LabelFrame(mainL,borderwidth=0, bg="#c3dde6", height=100, width=100)
calFrame.grid(row=1, column=0, sticky=NSEW)
cal=Calendar(calFrame, selectmode="day",firstweekday="monday",background="#0f8bff",foreground="black",disabledforeground="#a3bec7",bordercolor="grey",normalbackground="#d0f4ff",weekendbackground="#8ffeff",weekendforeground ="black" ,disabledbackground="99b3bc",year=int(datetime.datetime.now().strftime("%Y")),month=int(datetime.datetime.now().strftime("%m")), day=int(datetime.datetime.now().strftime("%d")))
cal.pack(pady=10)
getdat=Button(calFrame,text="Get This Date",bg="#00ffde", command=getCustomDate())
getdat.pack()
更新
感谢@j_4321 解决了我的问题,我创建了一个新的 python 文件和其中的代码 运行,我想要的自定义格式的日历日期选择器,它就像一个魅力,并提供所需的输出。
fresh.py:
from tkinter import *
from tkcalendar import *
root=Tk()
root.geometry("500x500")
def mainF():
global cal
def getDate():
date=cal.get_date()
print(date)
cal.pack(pady=20, padx=20)
butt=Button(root,text="Date Getter", bg="cyan",command=getDate).pack()
cal=Calendar(root,selectmode="day",date_pattern="dd-mm-y")
but=Button(root,text="Pick Date",command=mainF).pack()
root.mainloop()
但是在我的 main.py 中,相同的代码不起作用并给出以下错误消息:
<bound method Calendar.get_date of <tkcalendar.calendar_.Calendar object .!labelframe.!frame2.!frame.!frame2.!calendar>>
我不知道为什么会这样,也许我的 main.py 代码有问题,但我似乎无法找到它。
这是我的main.py代码:
from calendar import firstweekday
import csv, datetime
from tkinter import *
from tkcalendar import *
from tkinter import ttk
from PIL import Image, ImageTk
now=datetime.datetime.now().strftime("%d-%m-%Y")
f=open("Dr Nikhil Prescription App\Patient_Data.csv","r", newline="")
reader=csv.reader(f, delimiter=",")
L=[k[0] for k in reader]
try:
sndat=str(1+(int(L[-1])))
except ValueError:
sndat=1
f.close()
from tkinter import messagebox
def DataAdder2CSV():
global edate, eSNO, eage, egender, ename, ePID, econtact, ecomp, eallergy, ehistory, eR
e=edate.get()
a=eSNO.get()
d=eage.get()
f=egender.get()
b=ename.get()
c=ePID.get()
g=econtact.get()
h=ecomp.get(1.0,END)
i=eallergy.get(1.0,END)
j=ehistory.get(1.0,END)
k=eR.get(1.0,END)
data=[a,b,c,d,e,f,g,h,i,j,k]
file=open("Patient_Data.csv","a", newline="")
writer=csv.writer(file, delimiter=",")
writer.writerow(data)
file.close()
messagebox.showinfo("Prescription Generator", "Data has been saved to the database successfully!")
def PrescGen():
from tkinter import filedialog
root.filename=filedialog.askdirectory(initialdir="Documents", title="Choose Destination Folder")
'''
import win32com.client, os
psApp = win32com.client.Dispatch("Photoshop.Application")
psApp.Open("Presc_Template.psd")
doc = psApp.Application.ActiveDocument
layer_facts = doc.ArtLayers["GLAYER"]
text_of_layer = layer_facts.TextItem
text_of_layer.contents = "This is an example of a new text."
'''
messagebox.showinfo("Prescription Generator", "Prescription has been saved in the desired location successfully!")
def dispcal():
calFrame.grid(row=1, column=0,pady=60, sticky=NSEW)
cal.pack(pady=10,padx=50, fill="both", expand=True)
def getCustomDate():
print(cal.get_date)
getdat=Button(calFrame,text="Get This Date",bg="#00ffde", command=getCustomDate)
getdat.pack()
root=Tk()
root.config(bg="#add8e6")
megaF=LabelFrame(root,bg="#add8e6", borderwidth=0)
megaF.pack()
greet=Label(megaF,font="Arial 25",text="Prescription Generator", bg="#add8e6", fg="black").pack(pady=20)
dateF=Frame(megaF, padx=10, pady=10, bg="#c3dde6")
dateF.pack()
mega2F=Frame(megaF,bg="#c3dde6")
mega2F.pack()
date=Label(dateF,font="Arial 12",text="Date:", bg="#c3dde6").grid(row=0,column=0)
edate=Entry(dateF, width=10)
edate.insert(0,now)
edate.grid(row=0, column=1, padx=5)
CalIMG=ImageTk.PhotoImage(Image.open("D:\Coding\Python Scripts\Dr Nikhil Prescription App\cal.png"))
mainL=Frame(mega2F,borderwidth=0, padx=10, pady=10, bg="#c3dde6")
mainL.grid(row=0, column=0)
calFrame=Frame(mainL,borderwidth=0, bg="#c3dde6", height=200, width=100)
cal=Calendar(calFrame,
date_pattern="dd-mm-y",
selectmode="day",
firstweekday="monday",
background="#0f8bff",
foreground="black",
disabledforeground="#a3bec7",
bordercolor="grey",
normalbackground="#d0f4ff",
weekendbackground="#8ffeff",
weekendforeground ="black" ,
disabledbackground="99b3bc")
CalButt=Button(dateF, image=CalIMG, command=dispcal, borderwidth=0, bg="#c3dde6").grid(row=0, column=2, padx=5)
main2L=LabelFrame(mega2F,borderwidth=0, padx=10, pady=10, bg="#c3dde6")
main2L.grid(row=0, column=1,pady=20, padx=40)
PDlf=Frame(mainL, padx=10, pady=13, bg="#c3dde6")
PDlf.grid(row=0, column=0, sticky=NSEW)
sno=Label(PDlf,font="Arial 14",text="Sno:", bg="#c3dde6").grid(row=0,column=0, sticky=E)
eSNO=Entry(PDlf, width=3)
eSNO.insert(0,sndat)
eSNO.grid(row=0, column=1)
age=Label(PDlf,font="Arial 14",text="Age:", bg="#c3dde6").grid(row=1,column=0, sticky=E)
eage=Entry(PDlf, width=3)
eage.grid(row=1, column=1, pady=10)
gender=Label(PDlf,font="Arial 14",text="Gender:", bg="#c3dde6").grid(row=2,column=0, sticky=E)
egender=Entry(PDlf, width=3)
egender.grid(row=2, column=1)
name=Label(PDlf,font="Arial 14",text="Name:", bg="#c3dde6").grid(row=0,column=3, sticky=E)
ename=Entry(PDlf, width=15)
ename.grid(row=0, column=4)
Pid=Label(PDlf,font="Arial 14",text="PatientID:", bg="#c3dde6").grid(row=1,column=3, sticky=E)
ePID=Entry(PDlf, width=15)
ePID.grid(row=1, column=4, pady=10)
contact=Label(PDlf,font="Arial 14",text="Contact:", bg="#c3dde6").grid(row=2,column=3, sticky=E)
econtact=Entry(PDlf, width=15)
econtact.grid(row=2, column=4)
blank=Label(PDlf,font="Arial 14",text=" ", bg="#c3dde6").grid(row=1,column=2)
contentLF=LabelFrame(main2L, padx=10, pady=10, bg="#c3dde6", borderwidth=0)
contentLF.grid(row=0, column=2, sticky=SE)
blank=Label(PDlf,font="Arial 14",text=" ", bg="#c3dde6").grid(row=0,column=2)
complaint=Label(contentLF,font="Arial 14",text="Complaint:", bg="#c3dde6").grid(row=0,column=1, sticky=E)
ecomp=Text(contentLF, width=90, height=4)
ecomp.grid(row=0, column=2)
allergy=Label(contentLF,font="Arial 14",text="Allergy:", bg="#c3dde6").grid(row=1,column=1, sticky=E)
eallergy=Text(contentLF, width=90, height=2)
eallergy.grid(row=1, column=2, pady=10)
history=Label(contentLF,font="Arial 14",text="History:", bg="#c3dde6").grid(row=2,column=1, sticky=E)
ehistory=Text(contentLF, width=90, height=5)
ehistory.grid(row=2, column=2)
R=Label(contentLF,font="Arial 14",text="Diagnosis:", bg="#c3dde6").grid(row=3,column=1, sticky=E)
eR=Text(contentLF, width=90, height=12)
eR.grid(row=3, column=2, pady=10)
buttF=LabelFrame(main2L, bg="#c3dde6", borderwidth=0)
buttF.grid(row=4, column=2, sticky=E)
genPres=Button(buttF,font="Arial 12",text="Generate Prescription", bg="#ff80b9", command=PrescGen).grid(row=0, column=0, padx=10, sticky=E)
csvAdd=Button(buttF,font="Arial 12",text="Add to Database", bg="#49ff9a", command=DataAdder2CSV).grid(row=0, column=1,padx=10, sticky=E)
root.title("Prescription Generator")
root.state("zoomed")
root.mainloop()
首先,在
getdat=Button(calFrame,text="Get This Date",bg="#00ffde", command=getCustomDate())
您正在执行函数而不是将其作为参数传递,如 Why is the command bound to a Button or event executed when declared?.
然后,根据 Calendar 的文档字符串,它需要一个 date_pattern
选项
date_pattern : str date pattern used to format the date as a string. The default pattern used is babel's short date format in the Calendar's locale. A valid pattern is a combination of 'y', 'm' and 'd' separated by non letter characters to indicate how and in which order the year, month and day should be displayed. y: 'yy' for the last two digits of the year, any other number of 'y's for the full year with an extra padding of zero if it has less digits than the number of 'y's. m: 'm' for the month number without padding, 'mm' for a two-digit month d: 'd' for the day of month number without padding, 'dd' for a two-digit day Examples for datetime.date(2019, 7, 1): 'y-mm-dd' → '2019-07-01' 'm/d/yy' → '7/1/19'
所以在创建日历时只需在参数中传递 date_pattern="dd-mm-yyyy"
。
这是一个例子
from tkinter import Tk, Button
from tkcalendar import Calendar
def getCustomDate():
print(cal.get_date())
root = Tk()
cal = Calendar(root,
selectmode="day",
firstweekday="monday",
background="#0f8bff",
foreground="black",
disabledforeground="#a3bec7",
bordercolor="grey",
normalbackground="#d0f4ff",
weekendbackground="#8ffeff",
weekendforeground ="black",
disabledbackground="99b3bc",
date_pattern="dd-mm-yyyy")
cal.pack(pady=10)
getdat=Button(root, text="Get This Date",
bg="#00ffde", command=getCustomDate)
getdat.pack()
root.mainloop()