我想要一条闪烁着时钟秒数的短信。这个Link很有帮助,但不能解决我的问题。下面是我的小代码:
from tkinter import *
from datetime import datetime
import datetime as dt
import time
def change_color():
curtime=''
newtime = time.strftime('%H:%M:%S')
if newtime != curtime:
curtime = dt.date.today().strftime("%B")[:3]+", "+dt.datetime.now().strftime("%d")+"\n"+newtime
clock.config(text=curtime)
clock.after(200, change_color)
flash_colours=('black', 'red')
for i in range(0, len(flash_colours)):
print("{0}".format(flash_colours[i]))
flashing_text.config(foreground="{0}".format(flash_colours[i]))
root = Tk()
clock = Label(root, text="clock")
clock.pack()
flashing_text = Label(root, text="Flashing text")
flashing_text.pack()
change_color()
root.mainloop()这行代码:当函数每隔200s调用一次时,print("{0}".format(flash_colours[i]))会在控制台上打印交替的颜色。但是flashing_text标签的文本前景不会改变颜色。
有谁有解决这个问题的办法吗?谢谢!
请原谅我糟糕的编码。
发布于 2019-12-05 09:33:27
虽然您已经在for循环中更改了两次flashing_text的颜色,但tkinter事件处理程序(mainloop())只有在change_color()完成后收回控件时才能处理这些更改。因此,您只能看到红色的flashing_text (最后的颜色更改)。
要实现此目标,需要在change_color()中更改一次颜色。下面是修改后的change_color()
def change_color(color_idx=0, pasttime=None):
newtime = time.strftime('%H:%M:%S')
if newtime != pasttime:
curtime = dt.date.today().strftime("%B")[:3]+", "+dt.datetime.now().strftime("%d")+"\n"+newtime
clock.config(text=curtime)
flash_colors = ('black', 'red')
flashing_text.config(foreground=flash_colors[color_idx])
clock.after(200, change_color, 1-color_idx, newtime)发布于 2019-12-04 19:58:55
我会将它添加到一个类中,这样您就可以从每个回调中共享您的变量。
所以就像这样。
from tkinter import *
from datetime import datetime
import datetime as dt
import time
class Clock:
def __init__(self, colors):
self.root = Tk()
self.clock = Label(self.root, text="clock")
self.clock.pack()
self.flashing_text = Label(self.root, text="Flashing text")
self.flashing_text.pack()
self.curtime = time.strftime('%H:%M:%S')
self.flash_colours = colors
self.current_colour = 0
self.change_color()
self.root.mainloop()
def change_color(self):
self.newtime = time.strftime('%H:%M:%S')
if self.newtime != self.curtime:
if not self.current_colour:
self.current_colour = 1
else:
self.current_colour = 0
self.curtime = time.strftime('%H:%M:%S')
self.flashing_text.config(foreground="{0}".format(self.flash_colours[self.current_colour]))
self.clock.config(text=self.curtime)
self.clock.after(200, self.change_color)
if __name__ == '__main__':
clock = Clock(('black', 'red'))https://stackoverflow.com/questions/59174408
复制相似问题