Home > Article > Backend Development > How to Capture Screenshots in Linux Using Python Without External Dependencies?
In various Linux environments, the need arises to unobtrusively capture screenshots for documentation or analysis purposes. Utilizing Python's powerful scripting capabilities, we explore a scripting method for taking screenshots without revealing any visible distractions.
The Python script below harnesses GTK bindings to retrieve the screen resolution and pixel data without requiring external dependencies or visualization tools. This solution ensures compatibility with all X-based environments, ensuring a seamless integration across different Linux distributions.
<code class="python">import gtk.gdk # Fetch desktop window information w = gtk.gdk.get_default_root_window() sz = w.get_size() # Create a pixbuf for capturing the screen pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, sz[0], sz[1]) pb = pb.get_from_drawable(w, w.get_colormap(), 0, 0, 0, 0, sz[0], sz[1]) # Check if the pixbuf is successfully captured if pb is not None: save_path = "screenshot.png" print(f"Screenshot saved to {save_path}.") pb.save(save_path, "png") else: print("Unable to capture the screenshot. Retry the operation.")</code>
This script offers a non-intrusive solution for capturing screenshots on Linux using Python, making it a valuable tool for automation and image acquisition tasks.
The above is the detailed content of How to Capture Screenshots in Linux Using Python Without External Dependencies?. For more information, please follow other related articles on the PHP Chinese website!