代码之家  ›  专栏  ›  技术社区  ›  Nabil Haidar

无法实时刷新自定义tkinter帧

  •  0
  • Nabil Haidar  · 技术社区  · 3 年前

    我试图不断刷新CTkinter帧,但代码一直卡在 TS_Button_Update() 功能,而主窗口永远不会打开( print(countdown) 然而重复打印)。我最终还希望代码也能更新GUI的其他特性,例如基于变量的按钮颜色——有没有办法更改代码,使其实时自动刷新?

    以下是代码片段(整个程序太长,无法粘贴到此处):

    class HomeScreen(customtkinter.CTkFrame):
        def TS_Button_Update(self,TS_progress_Button,temperature):
            countdown = ser_ard1.readline().decode('ascii')
            countdown = countdown.replace('\n','')
            print(countdown)
            temperature.set(countdown)
            TS_progress_Button.configure(text = countdown)
            TS_progress_Button.after(2000,self.TS_Button_Update(TS_progress_Button,temperature))
        
        def __init__(self, master, **kwargs):
            super().__init__(master, **kwargs)
            global TS_progress_Button, temperature
            width, height = self.winfo_screenwidth(), self.winfo_screenheight()
            rrw = width/1920
            rrh= height/1080
            countdown = ser_ard1.readline().decode('ascii')
            countdown = countdown.replace('\n','')
            temperature = StringVar()
            temperature.set(countdown)
            print(countdown)
            
            TS_progress_Button=customtkinter.CTkLabel(self, fg_color=main_fg, bg_color=main_fg, text_color = 'white', width=rrw*225, height=rrh*20
                                                      , textvariable=temperature)
            TS_progress_Button.place(x=rrw*750,y=rrh*1000)
            self.TS_Button_Update(TS_progress_Button,temperature)
    

    我还尝试了其他变体,例如 self.update() 调用后 TS按钮更新() 这是第一次(并删除了内置循环),以及让函数在每次迭代时放置一个新标签,但运气不佳。有人能帮我弄清楚我做错了什么吗?

    1 回复  |  直到 3 年前
        1
  •  1
  •   Cosemuckel    3 年前

    打电话时 TS_progress_Button.after(2000,self.TS_Button_Update(TS_progress_Button,temperature)) ,您实际上并没有将引用传递给 TS_Button_Update 稍后执行,但在适当的位置调用它,这将导致函数陷入循环。

    将此行替换为 TS_progress_Button.after(2000, self.TS_Button_Update, TS_progress_Button, temperature) .

    这将调度延迟2000毫秒后调用的函数,通过 TS_progress_Button temperature 作为论据。

    关于其他gui组件

    可以使用相同的方法:

    def update_button_color():
        if some_condition:
            TS_progress_Button.configure(bg='red')
        else:
            TS_progress_Button.configure(bg='green')
        TS_progress_Button.after(1000, update_button_color) # The function will be called every second, since it calls itself
    
    # Call the function once to start the periodic updates
    update_button_color()