首页 > 解决方案 > Tkinter 代码有时运行缓慢,有时运行快速

问题描述

只是提醒一下,我对 Tkinter比较陌生。

我正在开发一个 Tkinter GUI,该 GUI 用于连接并运行一个用 C++ 编写的单独程序,该程序执行一些实验。GUI 允许用户设置所有实验,然后运行实验,并在它们发生时对其进行监控。

现在我正在努力让用户根据他们当前的工作来隐藏或显示 GUI 的不同部分。GUI 的一部分由 72 个按网格排列的按钮组成,用户可以单击任何按钮以显示从 JSON 文件中提取的一些信息(当程序加载时,而不是动态地),C++ 代码用于跑。

问题是,当我尝试显示带有 72 个按钮的部分时,如果在实验运行之前完成,则显示网格需要很长时间。这很奇怪,因为当实验运行时,网格几乎是瞬间出现的。当它运行缓慢时,GUI 可能需要 5 秒来绘制所有 72 个按钮,我可以看到它们一个一个地出现。

两次运行的代码完全相同。在这两种情况下,它都在同一个线程上运行。我实际上只是忘记并重新包装了包含按钮的框架,所以它不像每次重新显示该部分时我都在创建按钮,我只是重新包装框架。

不幸的是,我真的不知道我应该为这个问题发布的所有代码是什么,因为 GUI 跨越了无数文件中的数千行代码......但作为开始,有问题的直接代码可以显示或隐藏图形用户界面部分:

def showHideControlGrid(self):
    if self.grid_menu_var.get()==0:
        # The grid is currently being shown, so the user wants to hide it.
        self.control.GroupFrames[0].pack_forget()
        self.control.GroupFrames[1].pack_forget()
        if self.grid_menu_var.get() == 0 and self.movements_menu_var.get() == 0:
            #If both the grid and the movement controls are hidden then remove the middle section all together.
            self.midFrame.pack_forget()
    elif self.movements_menu_var.get()==0:
        # The grid is currently hidden, so the user wants to show it. The movement controls are also hidden so we must first repack the entire middle section again.
        self.rightFrame.pack_forget()
        
        self.midFrame.pack(side=LEFT,fill=BOTH,padx=10,pady=10)
        self.control.GroupFrames[0].pack(fill='x')
        self.control.GroupFrames[1].pack(fill='x')

        self.rightFrame.pack(fill=BOTH,padx=10,pady=10)
    else:
        # The grid is currently hidden, so the user wants to show it. The movement controls are currently displayed (meaning the middle section is packed) so we just need to re-pack the grid above the movement controls.
        self.control.GroupFrames[2].pack_forget()

        for w in self.control.GroupFrames:
            w.pack(fill='x')

请注意,GroupFrames[0] 和 GroupFrames[1] 包含放置网格的框架,而 GroupFrames[2] 包含放置一些移动控件的框架。但是,如果显示移动控件,它们总是显示在网格下方。

有没有人知道为什么网格有时绘制速度如此之慢而其他速度如此之快?

标签: pythonperformancetkinter

解决方案


推荐阅读