【发布时间】:2020-09-29 11:39:57
【问题描述】:
我正在创建一个简单的 GUI 来显示巴士到达时间和当前时间。但是,当我尝试显示时间并每秒刷新一次时,时间重复了window.after(1000, time)
下面是代码
import json
import datetime
from tkinter import *
window = Tk()
window.title("Welcome to the Smart Bus Stop test")
window.configure(bg='black')
frame = LabelFrame(window,bg='black',bd = 0)
frame.pack(anchor = NW, side = LEFT)
timeWidget = LabelFrame(window, bg ='black', bd =0)
timeWidget.pack(anchor = NE, side = RIGHT)
def time():
now = datetime.datetime.now()
Time = now.strftime("%H:%M")
Day = now.strftime("%A")
Date = now.strftime("%b %d, %Y")
displayTime = Label(timeWidget, text= Time, font=("Helvetica", 50), bg="black", fg="white")
displayTime.pack(anchor = E, side = TOP)
displayDay = Label(timeWidget, text= Day, font=("Helvetica", 15), bg="black", fg="white")
displayDay.pack(anchor = E, side = TOP)
displayDate = Label(timeWidget, text= Date, font=("Helvetica", 15), bg="black", fg="white")
displayDate.pack(anchor = E, side = TOP)
window.after(1000, time)
def data():
with open('bus_arrival.json', 'r') as json_file:
values = json.load(json_file)
z = len(values)
BusService = ['', '', '', '', '']
BusArr1 = ['', '', '', '', '']
BusArr2 = ['', '', '', '', '']
BusNo = Label(frame, text=" Bus ", font=("Helvetica", 30), bg="black", fg="white")
BusNo.grid(row=0, column=0)
NextBus = Label(frame, text=" Next Bus ", font=("Helvetica", 30), bg="black", fg="white")
NextBus.grid(row=0, column=1)
SubBus = Label(frame, text=" Subsequent Bus ", font=("Helvetica", 30), bg="black", fg="white")
SubBus.grid(row=0, column=2)
for x in range(z):
BusService[x] = values[x]["Bus Service"]
BusArr1[x] = values[x]["1st Bus"]
BusArr2[x] = values[x]["2st Bus"]
ServiceNo = Label(frame, text=BusService[x], font=("Helvetica", 30), bg="black", fg="white")
ServiceNo.grid(row=x+1, column=0)
Bus1 = Label(frame, text=BusArr1[x], font=("Helvetica", 30), bg="black", fg="white")
Bus1.grid(row=x+1, column=1)
Bus1 = Label(frame, text=BusArr2[x], font=("Helvetica", 30), bg="black", fg="white")
Bus1.grid(row=x+1, column=2)
window.after(1000, data)
time()
data()
window.mainloop()
【问题讨论】:
-
您应该在
time()之外创建标签并使用config(text=...)更新其文本。
标签: python-3.x tkinter