Объект Python/Tinker 'datetime.date' не имеет атрибута 'get' (введите дату в документ блокнота)

Я новый.

Чтобы получить представление о том, как работает базовое кодирование, я создал графический интерфейс, в котором конечный пользователь будет вводить текст в виджет ввода, нажимать кнопку, и текст будет отображаться в оболочке, сохраненной в блокноте.

Мой графический интерфейс имеет три кнопки;

  • Кнопка 1 сохранит текст, введенный в графическом интерфейсе, в блокнот и отобразит через оболочку.
  • Кнопка 2 - сохранить сегодняшнюю дату в блокноте и отобразить через оболочку.
  • Кнопка 3 открывает файл блокнота .exe

Я могу успешно сохранить текст в блокноте и открыть блокнот через приложение с графическим интерфейсом. Однако я не могу сохранить дату в блокноте.

Это пример кода, который отображает ошибку атрибута. (При нажатии кнопки 2)

 #030820, printing time  to shell and notepad # in progress
def button1Click():
    print (time.get)
    with open("Names101.txt", "a") as output:  #prints to notepad 
        output.write(time.get() + "\n") #prints to notepad
    
button1 = tk.Button(window, text=("Record Time"),width = 30, command=button1Click, bg="light blue")

Эта ошибка отображается

File "C:\Users\shane\AppData\Local\Programs\Python\Python38- 
32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:\Users\shane\source\repos\GUI input to Notepad\GUI input to 
Notepad\GUI_input_to_Notepad.py", line 16, in button1Click
print (time.get)
AttributeError: 'datetime.date' object has no attribute 'get'
The thread 'MainThread' (0x1) has exited with code 0 (0x0).
The program 'python.exe' has exited with code -1 (0xffffffff).

Это полный код моего приложения

import tkinter as tk
import datetime
import os #opens a text file 
window = tk.Tk()
window.title ("Shane's Text to NotePad Testing GUI")
window.geometry("400x150")
window.configure(bg="#3BB9FF")

time = datetime.date.today()
print (time)


#030820, printing time  to shell and notepad # in progress
def button1Click():
    print (time.get)
    with open("Names101.txt", "a") as output:  #prints to notepad 
        output.write(time.get() + "\n") #prints to notepad
        

button1 = tk.Button(window, text=("Record Time"),width = 30, command=button1Click, bg="light blue")



#button3 opens txt file
def button3Click():
    os.system("Names101.txt")

button3 = tk.Button(window, text=("Open Notepad file"),width=30, command=button3Click, bg="light green")






#030820, printing entry1 to shell and notepad 

entry1 = tk.Entry(window, width = 50)

def entry1get():    
    print (entry1.get())    #prints to shell
    with open("Names101.txt", "a") as output:  #prints to notepad
        output.write(entry1.get() + "\n")   #prints to notepad
    
                

button2 = tk.Button(window, text="Input text to notepad", width=30, command=entry1get, bg="#E6E6FA")
    
    

#030820 Label one 


label1 = tk.Label(text="Enter text below", font="bold" , bg="#3BB9FF")   




label1.pack() 
entry1.pack() 
button2.pack() 
button1.pack() 
button3.pack()



window.mainloop()

`

Льюис Моррис ответил на вопрос, ниже приведено решение

def button1Click():
print (time.strftime("%Y-%m-%d"))
with open("Names101.txt", "a") as output:  #prints to notepad 
    output.write(time.strftime("%Y-%m-%d") + "\n")  #prints to notepad
    

button1 = tk.Button(window, text=("Record Time"),width = 30, 
command=button1Click, bg="light blue")  

person Shane    schedule 04.08.2020    source источник
comment
можешь тоже написать код ошибки   -  person Cool Cloud    schedule 04.08.2020
comment
я наполовину сплю, но у вас есть time.get и time.get() один из них неправильный.   -  person Lewis Morris    schedule 04.08.2020
comment
@LewisMorris, скорее всего, и то, и другое, поскольку время - это класс datetime.date, и, следовательно, нет метода get().   -  person ewong    schedule 04.08.2020
comment
почему вы пытаетесь вызвать .get() для объекта datetime.date? Как вы думаете, что это делает?   -  person Bryan Oakley    schedule 04.08.2020


Ответы (2)


При печати дат вы можете использовать метод .strftime().

Это позволяет вам печатать и форматировать дату и время любым удобным для вас способом.

i.e

инициализировать вашу дату.

time = datetime.date.today()

а затем вызовите strftime() с переданными параметрами, такими как

time.strftime("%Y-%m-%d")

печать должна быть выполнена, как показано ниже

print(time.strftime("%Y-%m-%d"))

Полный список кодов strftime можно найти здесь.

https://www.programiz.com/python-programming/datetime/strftime

person Lewis Morris    schedule 04.08.2020

Переменная time инициализируется как:

time = datetime.date.today()

Согласно документам даты и времени, нет ни атрибута, ни класса. метод, который соответствует вашему использованию time.get или time.get().

Это изменение должно решить вашу проблему:

def button1Click():
    print (time)
    with open("Names101.txt", "a") as output:  #prints to notepad 
        output.write(str(time) + "\n") #prints to notepad
person coltonrusch    schedule 04.08.2020