我正在尝试使用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次。开启等待0.7秒,关闭等待0.3秒X3 ...
没有错误,我单击“显示隐藏”按钮,并且当for循环终止时,箭头只会消失。
答案 0 :(得分:3)
您不应使用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次)。
答案 1 :(得分:1)
请参阅How to make a flashing text box in tkinter?
在tkinter小部件上产生效果之前,for循环将完整执行。由于它要做的最后一件事是pack_forget(),所以什么也没出现