Объект Python / Tinker 'datetime.date' не имеет атрибута 'get' (дата ввода в блокноте c) - PullRequest
0 голосов
/ 04 августа 2020

Я новичок.

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

Мой GUI имеет три кнопки;

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

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

Это пример кода, который отображает ошибку атрибута. (При нажатии кнопки 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")  

Ответы [ 2 ]

3 голосов
/ 04 августа 2020

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

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

т.е.

инициализируйте дату.

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

0 голосов
/ 04 августа 2020

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

time = datetime.date.today()

Согласно datetime docs , нет атрибута или метода класса, который соответствует вашему использованию 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
...