Tkinter long-running window freezes

MRAB python at mrabarnett.plus.com
Wed Feb 24 08:07:24 EST 2021


On 2021-02-24 11:35, John O'Hagan wrote:
> Hi list
> 
> I have a 3.9 tkinter interface that displays data from an arbitrary
> number of threads, each of which runs for an arbitrary period of time.
> A frame opens in the root window when each thread starts and closes
> when it stops. Widgets in the frame and the root window control the
> thread and how the data is displayed.
> 
> This works well for several hours, but over time the root window
> becomes unresponsive and eventually freezes and goes grey. No error
> messages are produced in the terminal.
> 
> Here is some minimal, non-threaded code that reproduces the problem on
> my system (Xfce4 on Debian testing):
> 
> from tkinter import *
> from random import randint
> 
> root = Tk()
> 
> def display(label):
>      label.destroy()
>      label = Label(text=randint(0, 9))
>      label.pack()
>      root.after(100, display, label)
> 
> display(Label())
> mainloop()
>   
> This opens a tiny window that displays a random digit on a new label
> every .1 second. (Obviously I could do this by updating the text rather
> than recreating the label, but my real application has to destroy
> widgets and create new ones).
> 
> This works for 3-4 hours, but eventually the window freezes.
> 
> The process uses about 26 Mb of memory at first, and this gradually
> increases to around 30 or so by the time it freezes.
> 
> Any ideas what could be causing this, or even how to approach debugging
> or workarounds?
> 
The problem might be that you're adding the label using .pack but not 
removing it with .pack_forget when you destroy it.

Try doing both:

from tkinter import *
from random import randint

root = Tk()

def display(label):
     if label is not None:
         label.pack_forget()
         label.destroy()

     label = Label(text=randint(0, 9))
     label.pack()
     root.after(100, display, label)

display(None)
mainloop()


More information about the Python-list mailing list