我正在使用Tkinter和Python制作一款时钟。
我的目标是让时钟运行并自动检查JSON文件(包含时钟的视觉设置)是否已更新。如果JSON文件已更新,则时钟将实时更新。
但事实并非如此。我必须更新JSON文件,关闭时钟程序,然后重新打开时钟程序。只有在这种情况下,更改后的JSON设置才会生效。 clock.py
我的目标是让时钟运行并自动检查JSON文件(包含时钟的视觉设置)是否已更新。如果JSON文件已更新,则时钟将实时更新。
但事实并非如此。我必须更新JSON文件,关闭时钟程序,然后重新打开时钟程序。只有在这种情况下,更改后的JSON设置才会生效。 clock.py
from tkinter import *
from datetime import datetime
from settings import *
# Updates the program and clock settings
def tick():
time_string = datetime.now().strftime(time_format)
date_string = datetime.now().strftime(date_format)
root.config(bg=background_color)
container.configure(bg=background_color)
current_time.configure(text=time_string,
font=(time_font, time_size, time_weight, time_slant),
fg=time_color,
bg=background_color)
current_date.configure(text=date_string,
font=(date_font, date_size, date_weight, date_slant),
fg=date_color,
bg=background_color)
current_time.after(1, tick)
# TKInterface
root = Tk()
root.title(window_title)
# Binds 'Esc' key to exit program
root.bind('<Escape>', exit)
# Runs program in full-screen
if full_screen:
root.attributes('-fullscreen', True)
root.config(cursor='none')
# Creates container to hold time and date
container = Frame(root)
current_time = Label(container)
current_date = Label(container)
container.pack(expand=True)
current_time.pack()
current_date.pack()
tick()
root.mainloop()
settings.py
import os
import json
with open('settings.json') as json_settings:
settings = json.load(json_settings)
# Window
full_screen = settings['window']['full_screen']
window_title = settings['window']['window_title']
# Background
background_color = settings['background']['color']
# Time
time_font = settings['time']['font']
time_size = settings['time']['size']
time_weight = settings['time']['weight']
time_slant = settings['time']['slant']
time_color = settings['time']['color']
time_format = settings['time']['format']
# Date
date_font = settings['date']['font']
date_size = settings['date']['size']
date_weight = settings['date']['weight']
date_slant = settings['date']['slant']
date_color = settings['date']['color']
date_format = settings['date']['format']
settings.json
{
"window": {
"full_screen": false,
"window_title" : "chronoberry"
},
"background": {
"color": "black"
},
"time": {
"font": "arial",
"size": 70,
"weight": "bold",
"slant": "roman",
"color": "white",
"format": "%-I:%M:%S %p"
},
"date": {
"font": "arial",
"size": 20,
"weight": "normal",
"slant": "roman",
"color": "white",
"format": "%A, %B %-d %Y"
}
}
期望效果:
如果我在JSON文件中更改背景颜色并保存,我的时钟应该能够在运行时更新其颜色。
更改背景颜色之前
更改背景颜色之后
我尝试过的方法:
- 使用importlib.reload()重新导入settings.py模块,但是settings.py模块不是有效的参数。
- 打开settings.json,从中读取数据,然后关闭它,再次打开。但是,一旦文件关闭,就无法再次打开它。
after(1, ...)
在1毫秒后运行,而不是一秒钟?由于你的时钟只有一秒钟的分辨率,你让CPU做了比必要更多的工作。 - Bryan Oakley