如何使用Raspberry Pi在tkinter窗口中显示RTC库DS1302的时间和日期

时间:2019-04-07 15:29:39

标签: python-2.7 tkinter

我是新手,我对此表示怀疑。我使用库RTC_DS1302获取PC时间,并使用Raspberry Pi将其存储在RTC DS1302中。我的问题是如何在tkinter窗口中显示时间和日期,以及每次时间和日期更改时都进行更新,所以我无法做到这一点。我留下了获得时间和日期的代码。在此链接中,您可以找到库。

https://github.com/ksaye/IoTDemonstrations/blob/master/RTC_DS1302/RTC_DS1302.py

这是代码

import RTC_DS1302
import os
import time

ThisRTC = RTC_DS1302.RTC_DS1302()

Data = ThisRTC.ReadRAM()
print("Message: " + Data)
DateTime = { "Year":0, "Month":0, "Day":0, "DayOfWeek":0, "Hour":0, "Minute":0, "Second":0 }
Data = ThisRTC.ReadDateTime(DateTime)

print("Date/Time: " + Data)
print("Year: " + format(DateTime["Year"] + 2000, "04d"))
print("Month: " + format(DateTime["Month"], "02d"))
print("Day: " + format(DateTime["Day"], "02d"))
print("DayOfWeek: " + ThisRTC.DOW[DateTime["DayOfWeek"]])
print("Hour: " + format(DateTime["Hour"], "02d"))
print("Minute: " + format(DateTime["Minute"], "02d"))
print("Second: " + format(DateTime["Second"], "02d")) 

ThisRTC.CloseGPIO()

1 个答案:

答案 0 :(得分:0)

tkinter具有功能after(time_in_ms, function_name),可让您延迟运行功能。在此功能中,您可以更新Labels中的文本并执行after(time_in_ms, function_name),以便一段时间后它将运行相同的功能。

使用after()显示当前时间的示例

import tkinter as tk # Python 3.x
from datetime import datetime


def update_time():
    # update displayed time
    current_time = datetime.now()
    current_time_str = current_time.strftime('%Y.%m.%d  %H:%M:%S')
    label['text'] = current_time_str

    # run update_time again after 1000ms (1s)
    root.after(1000, update_time)

# --- main ---

root = tk.Tk()

label = tk.Label(root)
label.pack()

update_time()

root.mainloop()

More of my examples with after()