When you need to unobtrusively capture screenshots for automation or documentation purposes, using Python on a Linux system is an effective solution. Here's how you can do it:
The goal is to create a Python script capable of taking screenshots and saving them without any visible user interface (GUI) intervention.
To achieve this, we'll harness the power of GTK (GIMP Toolkit), a cross-platform graphics library commonly used in Linux environments. GTK provides access to the underlying graphics stack, enabling us to perform tasks such as screenshot capture.
Here's a concise and robust Python script that utilizes GTK for screenshotting:
<code class="python">import gtk.gdk # Get the default root window w = gtk.gdk.get_default_root_window() # Determine the screen size sz = w.get_size() # Create a pixbuf object pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, sz[0], sz[1]) # Capture the window screenshot pb = pb.get_from_drawable(w, w.get_colormap(), 0, 0, 0, 0, sz[0], sz[1]) if pb: # Save the screenshot as a PNG file pb.save("screenshot.png", "png") print("Screenshot saved to screenshot.png.") else: print("Unable to get the screenshot.")</code>
The above is the detailed content of How to Capture Screenshots in Linux Using Python?. For more information, please follow other related articles on the PHP Chinese website!