我正在尝试使用 pack() 和 pack_forget() 刷新图像。
我们正在打造一辆定制 BMW,车灯使用 Raspberry Pi 运行。我有使用 gpiozero 的 LED 信号灯,但现在我需要在仪表板上的显示器上显示它。我可以在函数中分别使用 Label.pack_forget() 和 Label.pack() 隐藏和显示图像,但我无法让它闪烁。我试过下面的代码。
这个有效:
def showBG():
background_label.pack()
def hideBG():
background_label.pack_forget()
hideBttn = tk.Button(window, text="Hide Arrow", command = hideBG)
showBttn = tk.Button(window, text="Show Arrow", command = showBG)
这不是:
import tkinter as tk
from time import sleep
def flashBG():
for i in range(0, 3):
background_label.pack()
sleep(.7)
background_label.pack_forget()
sleep(.3)
showHideBttn = tk.Button(window, text = "Flash Arrow", command = flashBG)
第一个示例按预期显示和隐藏箭头:按下隐藏按钮它消失,按下显示按钮它出现。
第二个示例应该像汽车仪表板上的信号灯一样闪烁 3 次。 ON 等待 0.7 秒,OFF 等待 0.3 秒 X3...
没有错误,我单击显示隐藏按钮,当 for 循环终止时,箭头就消失了。
最佳答案
你不应该使用 pack()
和 pack_forget()
来模拟闪烁,因为如果有多个小部件,标签可能不会放在同一个位置同一个容器。
此外,使用 sleep()
将阻止 mainloop()
处理未决事件,从而导致 background_label
未更新。
你应该改变标签的前景色来模拟闪烁:
创建标签后先保存前景色和背景色:
flash_colors = (background_label.cget('bg'), background_label.cget('fg'))
# then flash_colors[0] is label background color
# and flash_colors[1] is label foreground color
然后修改flashBG()
如下:
def flashBG(count=0, color_idx=0):
# set label text color to background color (color_idx=0) to hide the label
# or to foreground color (color_idx=1) to show the label
background_label.config(fg=flash_colors[color_idx])
if count < 5:
# execute flashBG() again after 300ms or 700ms based on the color of the label
window.after(300 if color_idx==0 else 700, flashBG, count+1, 1-color_idx)
flashBG(...)
将被执行 6 次(OFF 3 次,ON 3 次)。
关于python - 在 python 中制作图像 flash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55816559/