如何闪烁tkinter标签的次数有限,且仅当条件为m时

2024-05-19 00:21:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经为这个答案中给出的一个闪烁的tkinter标签运行了一个很好的例子:Flashing Tkinter Labels

然而,当我试图增加一些复杂性时,它失败了。在

首先,我需要它只在满足某些条件时闪烁(这是一个警报,所以,它应该只在警报状态下闪烁,而不是在正常情况下)。在

这是我想做的事情的基本版本。在

import Tkinter as tk
import tkFont
import epics

global root

class AlarmGUI:
    def __init__(self,parent):
        self.ending = False

        self.crhl = tk.Label(text='CFHT RH',bg='light blue')
        self.crhl.grid(row=1, column=2, 
                        padx=20, pady=20, sticky=tk.W)
        self.crhw = tk.Label(text='something',font=("Helvetica", 25,"bold"),bg='light blue')
        self.crhw.grid(row=2,column=0, sticky=tk.W)

        self.cfht()

    def flash(self):
        bg = self.crhw.cget('background')
        fg = self.crhw.cget('foreground')
        self.crhw.configure(background=fg,foreground=bg)
        self.crhw.after(1000,self.flash)  

    def cfht(self):
        #This reads in the value that is being tested
        crh = epics.caget('ws:wsHumid')    #Read in CFHT Relative Humidity

        #Here, I display the value 'crh'
        self.crhw.grid(row=2, column=2,sticky=tk.W+tk.E+tk.N+tk.S)
        self.crhw.configure(text=crh,fg='Red',bg='Gray')

        #Now I need to determine if the value crh is in an alarm state
        if (crh > 85):  #If the value is over 85, I need the label to flash.
          self.crhw.flash()

        #Then this keeps checking the humidity value
        self.crhw.after(30000,cfht)

def main():
    global root

    root = tk.Tk()
    gui = AlarmGUI(root)
    root.mainloop()

if __name__ == '__main__':
    main() 

我也试过让flash功能只闪一定次数。当我说这个(下面),它不会闪烁。它只在屏幕上打印30次,然后在gui出现在屏幕上之前大约需要30秒,并且不会闪烁:

^{pr2}$

Tags: thetextimportselfvaluedefcolumnroot
1条回答
网友
1楼 · 发布于 2024-05-19 00:21:45

你很亲密。您需要记住,after需要一个函数的引用。当您执行类似after(..., self.flash(count))的操作时,在调用after之前,正在调用函数。或者,更准确地说,你连续调用它31次,每次都将结果(None)给after,从而创建31个什么都不做的工作。在

after允许您在调用的对象中包含其他参数:

self.crhw.after(1000, self.flash, count)

面向对象方法

现在正是使用python面向对象特性的最佳时机。{label}你不能创建一个你自己的应用程序的flashing方法。这也使得你很容易拥有尽可能多的闪光标签。在

^{pr2}$

您可以像普通的Label一样使用它:

self.crhw = FlashableLabel(...)

你可以这样闪:

self.crhw.flash(0)

相关问题 更多 >

    热门问题