导入时间和日期



第一次玩Tkinter并使用我在网络上找到的一些代码,我将构建一个基本的应用程序来了解所使用的术语。我想将日期和时间导入我的 GUI 窗口。我已经设法让时间出现在窗口中,但没有这样的运气与日期。我可以在命令行中获取打印日期,仅此而已。

我知道这对某些人来说很简单,任何帮助将不胜感激。我正在使用Python 2.7。希望我正确使用这个网站!!干杯,B。

from Tkinter import *
import tkMessageBox
from datetime import datetime 
import ttk
username = ("admin")
password = ("")

def try_login():
print("Trying to login...")
if username_guess.get() == username:
tkMessageBox.showinfo("COMPLETE", "You Have Now Logged In.", icon="info")
else:
tkMessageBox.showinfo("-- ERROR --", "Please enter valid infomation!", icon="warning")
#Gui Things
window = Tk()
#Creating the username & password entry boxes
username_text = Label(text="Username:", bg='lightgrey')
username_guess = Entry()
password_text = Label(text="Password:", bg='lightgrey')
password_guess = Entry(show="*")
#attempt to login button
attempt_login = Button(text="Login", command=try_login)
attempt_login.pack(side="bottom", fill='none', expand=False, ipadx=0, ipady=0)
username_text.pack()
username_guess.pack()
password_text.pack()
password_guess.pack()
attempt_login.pack()
#Main Starter
window.mainloop()
##time1 = ''
##clock = Label(font=('times', 10, 'bold'), bg='lightgrey')
##clock.pack(side="bottom", fill='both', expand=False, ipadx=0, ipady=0)
##
##
##def tick():
##    global time1
##    time2 = time.strftime('%H:%M:%S')
##    if time2 != time1:
##        time1 = time2
##    clock.config(text=time2)
##    clock.after(200, tick)
##tick()

您还没有显示您尝试获取时间的内容,所以我不知道到目前为止您的方法是什么,但是使用time模块,您可以轻松获取日期和时间。很好地包括格式,这是获取日期和时间的简单方法:

import time
d_and_t=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

有关其工作原理的信息,请参阅时间模块文档。
下面是一个制作每秒更新一次的 tkinter 时钟的示例:

from time import localtime, strftime, sleep #import various time functions
from tkinter import * #import tkinter
def disp(root): #a time updating function
Label(root, text=strftime("%Y-%m-%d %H:%M:%S", localtime()), fg='green', bg='purple', font=('Times', 20, 'bold')).grid(row=0, column=0) #see below explanation
root.after(1000, lambda:disp(root)) #after 1 second, run this again
root=Tk() #create a window
root.title('Clock') #title it Clock
disp(root) #start the updating process
mainloop() #start the tkinter mainloop

第4行说明:

  • Label(...)- 创建标签实例
  • root- 将其固定到主窗口
  • text=strftime(...)- 将文本分配给一些时间格式的文本
  • "%Y-%m-%d %H:%M:%S"- 我们如何格式化时间:YYYY-MM-DD HH:MM:SS
  • localtime()- 返回本地时间
  • fg='green', bg='purple', font=('Times', 20, 'bold')- 将文本格式化为绿色,紫色背景,粗体时代字体,20磅
  • .grid(row=0, column=0)- 每次都将其放在同一位置,以便它位于顶部

最新更新