Get window position and size in python with Xlib - python

I need to find window position and size, but I cannot figure out how. For example if I try:
id.get_geometry() # "id" is Xlib.display.Window
I get something like this:
data = {'height': 2540,
'width': 1440,
'depth': 24,
'y': 0, 'x': 0,
'border_width': 0
'root': <Xlib.display.Window 0x0000026a>
'sequence_number': 63}
I need to find window position and size, so my problem is: "y", "x" and "border_width" are always 0; even worse, "height" and "width" are returned without window frame.
In this case on my X screen (its dimensions are 4400x2560) I expected x=1280, y=0, width=1440, height=2560.
In other words I'm looking for python equivalent for:
#!/bin/bash
id=$1
wmiface framePosition $id
wmiface frameSize $id
If you think Xlib is not what I want, feel free to offer non-Xlib solution in python if it can take window id as argument (like the bash script above). Obvious workaround to use output of the bash script in python code does not feel right.

You are probably using reparenting window manager, and because of this id window has zero x and y. Check coordinates of parent window (which is window manager frame)

Liss posted the following solution as a comment:
from ewmh import EWMH
ewmh = EWMH()
def frame(client):
frame = client
while frame.query_tree().parent != ewmh.root:
frame = frame.query_tree().parent
return frame
for client in ewmh.getClientList():
print frame(client).get_geometry()
I'm copying it here because answers should contain the actual answer, and to prevent link rot.

Here's what I came up with that seems to work well:
from collections import namedtuple
import Xlib.display
disp = Xlib.display.Display()
root = disp.screen().root
MyGeom = namedtuple('MyGeom', 'x y height width')
def get_absolute_geometry(win):
"""
Returns the (x, y, height, width) of a window relative to the top-left
of the screen.
"""
geom = win.get_geometry()
(x, y) = (geom.x, geom.y)
while True:
parent = win.query_tree().parent
pgeom = parent.get_geometry()
x += pgeom.x
y += pgeom.y
if parent.id == root.id:
break
win = parent
return MyGeom(x, y, geom.height, geom.width)
Full example here.

In the same idea as #mgalgs, but more direct, I ask the root window to translate the (0,0) coordinate of the target window :
# assuming targetWindow is the window you want to know the position of
geometry = targetWindow.get_geometry()
position = geometry.root.translate_coords(targetWindow.id, 0, 0)
# coordinates are in position.x and position.y
# if you are not interested in the geometry, you can do directly
import Xlib.display
position = Xlib.display.Display().screen().root.translate_coords(targetWindow.id, 0, 0)
This gives the position of the client region of the targeted window (ie. without borders, title bar and shadow decoration created by the window manage). If you want to include them, replace targetWindow with targetWindow.query_tree().parent (or second parent).
Tested with KUbuntu 20.04 (ie KDE, Plasma and KWin decoration).

Related

Mouse Coordinates in Graph Window

I'm trying to figure out how to find the mouse coordinates when clicking on the graph window a few times.
So far I've tried
mx ,my = win.mouseX(), win.mouseY() and it tells me that the Nonetype is not callable. I've seen other posts involving tkinter, but I am not using that library even though I see that it's easier. Some more example code is as follows:
from graphics import *
win = GraphWin("test", 300, 300)
for i in range(3):
win.getMouse()
mx, my = win.mouseX(), win.mouseY()
print(mx,my)
I want the above code to have the user click on the window and print the regarding mouse coordinates. Eventually I want to store these coordinates, but I think I can figure that out.
win.getMouse() returns a Point which you can get coordinates from like this:
from graphics import *
win = GraphWin("test", 300, 300)
for i in range(3):
point = win.getMouse()
mx, my = point.getX(), point.getY()
print(mx,my)

How to capture image (screenshot) of tkinter window on MacOS

I have created a GUI app in Python tkinter for analyzing data in my laboratory. There are a number of buttons, figures, and canvas widgets. It would be helpful to take a screenshot of the entire window ('root') using just a single button that saves the filename appropriately. Example using Mac's built-in "screenshot" app here.
Related questions here, here, and here, but none worked successfully. The final link was almost successful, however the image that is saved is my computer's desktop background. My computer is a Mac, MacOS Monterey 12.0.1.
'root' is the tkinter window because
root = tk.Tk()
appears at the beginning of the script, analogous to 'window' in the example here. I'm using PIL.ImageGrab in the code sample below.
This is the current code, which takes an unhelpful screenshot of my desktop background,
def screenshot():
# retrieve the time string to use as a filename
file_name = root.time_string[-6:]
full_file_name = file_name + '_summary' + '.png'
x = root.winfo_rootx() + root.winfo_x()
y = root.winfo_rooty() + root.winfo_y()
x1 = x + root.winfo_width()
y1 = y + root.winfo_height()
ImageGrab.grab().crop((x, y, x1, y1)).save(full_file_name)
I create the button like so:
screenshot_btn = tk.Button(root, text='Screenshot', command=lambda: screenshot(), font=('Verdana', 24), state=DISABLED)
And I place the button in 'root' like this:
screenshot_btn.grid(row=11, column=3)
[This is my first post at stackoverflow. I apologize in advance if I did not follow all the guidelines perfectly on the first try. Thanks for your patience.]
First, I didn't have an issue with the grab showing my desktop, but it was showing an improperly cropped image.
I have found a hacky solution. The issues appears to be with the resolution. So the dimensions need some scaling.
What I did was get the output from ImageGrab.grab().save(full_file_name) ( no cropping ) and measure the size of the desired image area in pixels. These dimensions will be called x_pixels and y_pixels.
Then I measured that same area on the actual window in screen units. I did this by bringing up the mac screenshot tool which shows the dimensions of an area. I then call these dimensions x_screen and y_screen. Then I modified your screenshot function as follows.
def screenshot():
# retrieve the time string to use as a filename
file_name = root.time_string[-6:]
full_file_name = file_name + '_summary' + '.png'
x = root.winfo_rootx()
y = root.winfo_rooty()
x1 = x + root.winfo_width()
y1 = y + root.winfo_height()
x_pixels = 337
y_pixels = 79
x_screen = 171
y_screen = 41
x = x*(x_pixels/x_screen)
y = y*(y_pixels/y_screen)
x1 = x1*(x_pixels/x_screen)
y1 = y1*(y_pixels/y_screen)
ImageGrab.grab().crop((x, y, x1, y1)).save(full_file_name)
Notice I also removed +root.winfo_x() and +root.winfo_y()
The result is shown below. It's not perfect, but I believe if I more carefully measured the pixels at the bounds of the screenshot and window the scaling would be improved.
Do you by chance have a "Retina" monitor? ImageGrab fails to take into account the 144 DPI image it collects from the Mac's screencapture command. You can compensate for this by multiplying all the x, y, x1, y1 values by 2 (but you may still miss a bit if you need to account for the Mac window titlebar).
Alternatively, use the pyscreenshot package (or steal its code...). It uses the "-R" option of screencapture to get the proper bounds for the image. Works on extended monitors like mine where the x co-ord is < 0 ('cause it's to the left of the main monitor).

PyQT Painter drawing Polygons

In my QT application I'm drawing lots of polygons like this:
I'm animating these, so some polygons will receive a new color. This animation runs 4-5 times per second.
However, calling the paintEvent() of the Qt.Painter() 4-5 times/second redraws ALL polygons which results in performance issues. Its only updated once a second, which is too slow. As you may see in the picture below, only some polygons in the first 12 rows needs to be updated:
[![enter image description here][2]][2]
In the QT docs I have read that you can't really save the state of the things you've already drawn. So you have to redraw everything again. Am I missing something? Is there a trick to still achieve this?
This is what my paintEvent() basically looks like (simplified, reduced cyclomatic complexity)
for y in range(len(self.array)):
for x in range(len(self.array[0])):
if(this): # simplified to reduce cyclomatic complexity
painter.setBrush(QBrush(QColor(20, 0, 255)))
elif(that):
painter.setBrush(QBrush(QColor(175, 175, 175)))
else:
painter.setBrush(QBrush(QColor(0, 0, 0)))
hexa_size = self.array[y][x]
hexas = createHexagon(x, y, hexa_size) # external functions to calculate the hexagon size and position
painter.drawPolygon(hexas)
painter.end()
call (update on each Pin change):
while True:
while(stempel.readPin(0) == 0):
QApplication.processEvents()
time.sleep(0.01)
self.draw_area.update() # Pin state changed, update polygons
while(stempel.readPin(0) == 1):
QApplication.processEvents()
time.sleep(0.01)
Qt allows scheduling an update for only a portion (region) of the widget, thus optimizing the result. This requires two step:
calling update(QRect) with an appropriate rectangle that covers only the part of the widget that requires repainting;
checking the event.rect() and then implement painting in order to paint only that region;
If you know for sure that only the first X rows are going to change color, then:
self.draw_area.update(
QRect(0, 0, self.draw_area.width(), <height of the repainted rows>)
Then, in the paintEvent:
if event.rect().bottom() < <height of the repainted rows>:
rowRange = range(indexOfTheLastRowToRepaint + 1)
else:
rowRange = range(len(self.array))
Note that another solution could be using QPicture, which is a way to "serialize" a QPainter in order to improve performance and avoid unnecessary computations.
class DrawArea(QWidget):
cache = None
def paintEvent(self, event):
if not self.cache:
self.cache = QPicture()
cachePainter = QPainter(self.cache)
# draw on the painter
cachePainter.end()
painter = QPainter(self)
painter.drawPicture(0, 0, self.cache)
def resizeEvent(self, event):
self.cache = None
The code above is very minimalistic, you might create multiple QPictures for every group of row and then decide which one paint whenever you require it, even by combining the event.rect() checking as explained above.
The major benefit of this technique is that QPainter usually processes a QPicture pretty fast, so you don't have to do all computations required for rows, polygons, etc.
Finally, the image you provided seems very repetitive, almost like a texture. In that case, you might consider using a QPixmap for each group of rows and then create a QBrush with that QPixmap. In that case, you'll only need to call painter.fillRect(self.rect(), self.textureBrush).
Solved it myself by using a QGraphicsScene + QGraphicsView:
self.scene = QGraphicsScene()
self.graphicView = QGraphicsView(self.scene, self)
Creating a list where all polygons are being saved:
self.polygons = [ [0] * len(array[0]) for _ in range(len(array))]
Initial drawing of all polygons:
for y in range(len(array)):
for x in range(len(array[0])):
polygon_size = self.array[y][x]
polygon = createPoly(x, y, polygon_size)
self.polygons[y][x] = self.scene.addPolygon(polygon, QPen(Qt.NoPen), QBrush(Qt.black))
if(y % 50 == 0): QApplication.processEvents()
Update rows indivudually:
for poly_size in active_rows:
for active_row in active_rows[poly_size]:
for x in range(0, len(array[0])):
if(array[active_row][x] == int(poly_size)):
self.polygons[active_row][x].setBrush(QBrush(QColor(20, 0, 255)))
if(array[active_row - 2][x] > 0 and array[active_row - 2][x] == int(poly_size)):
self.polygons[active_row - 2][x].setBrush(QBrush(QColor(175, 175, 175)))

(Instantiating an array of Buttons, but only one works

I'm trying to create a GUI for a virtual board for the game Go. There should be an nxn grid of tiles where a player can place a stone, either black or white. Clicking on a tile will make it change from tan(the default) to black, click again to white, and click a third time to go back to tan. Player one can click once on a spot to place a stone there, and player two can click twice (you need to remove stones later, so three clicks resets it). I created a tile object and then used a nested for loop to instantiate 9 by 9 of them. Unfortunately, running the code only seems to produce 1 functional tile, not 81. This code should work on any python machine (I'm using Python 3.4), so you can try to run it and see for yourself. Can anyone point out the reason the loop is only running once?
from tkinter import *
window = Tk()
n = 9
"""
A tile is a point on a game board where black or white pieces can be placed. If there are no pieces, it remains tan.
The basic feature is the "core" field which is a tkinter button. when the color is changed, the button is configured to represent this.
"""
class tile(object):
core = Button(window, height = 2, width = 3, bg = "#F4C364")
def __init__(self):
pass
"""the cycle function makes the tile object actually change color, going between three options: black, white, or tan."""
def cycle(self):
color = self.core.cget("bg")
if(color == "#F4C364"): #tan, the inital value.
self.core.config(bg = "#111111")#white.
elif (color == "#111111"):
self.core.config(bg = "#DDDDDD")#black.
else:
self.core.config(bg = "#F4C364")#back to tan.
board = [] #create overall array
for x in range(n):
board.append([])#add subarrays inside it
for y in range(n):
board[x].append(tile())#add a tile n times in each of the n subarrays
T = board[x][y] #for clarity, T means tile
T.core.config(command = lambda: T.cycle()) #I do this now because cycle hadn't been defined yet when I created the "core" field
T.core.grid(row = x, column = y) #put them into tkinter.
window.mainloop()
As mhawke points out in his answer you need to make the core an instance variable, so that each Tile gets its own core.
And as I mention in my comment above, you also need to fix the Button's command callback function. The code you use in your question will call the .cycle() method of the current value of T, which happens to be the last tile created. So no matter where you click only the last tile changes color. One way to fix that is to pass the current tile as a default argument of the lambda function when you create it. But because you are using OOP to create your Tile there's a better way, which you can see below.
I've made a few modifications to your code.
Although many Tkinter examples use from tkinter import * it's not a good practice. When you do from some_module import * it brings all of the names from some_module into the current module (your script), which means you could accidentally override those names with your own names. Even worse, if you do import * with multiple modules each new module's names can clash with the previous module's names, and you have no way of knowing that's happened until you start getting mysterious bugs. Using import tkinter as tk means you need to do a little more typing, but it makes the resulting program less bug-prone and easier to read.
I've modified the __init__ method so that it is called with the window and the (x, y) location of the tile (it's customary to use x for the horizontal coordinate and y for the vertical coordinate). Each Tile object now keeps track of its current state, where 0=empty, 1=black, 2=white. This makes it easier to update the colors. And because we've passed in the window and (x, y) we can use that info to add the tile to the grid. The tile also remembers the location (in self.location), which may come in handy.
I've modified the cycle method so that it updates both the background color and the activebackground of the tile. So when the mouse hovers over the tile it changes to a color that's (roughly) halfway between its current color and the color it will turn if you click it. IMO, this is nicer than the tile always turning pale grey when the mouse hovers over it.
I've also optimized the code that creates all the tiles and stores them in the board list of lists.
import tkinter as tk
colors = (
#background, #activebackground
("#F4C364", "#826232"), #tan
("#111111", "#777777"), #black
("#DDDDDD", "#E8C8A8"), #white
)
class Tile(object):
""" A tile is a point on a game board where black or white pieces can be placed.
If there are no pieces, it remains tan.
The basic feature is the "core" field which is a tkinter button.
when the color is changed, the button is configured to represent this.
"""
def __init__(self, win, x, y):
#States: 0=empty, 1=black, 2=white
self.state = 0
bg, abg = colors[self.state]
self.core = tk.Button(win, height=2, width=3,
bg=bg, activebackground=abg,
command=self.cycle)
self.core.grid(row=y, column=x)
#self.location = x, y
def cycle(self):
""" the cycle function makes the tile object actually change color,
going between three options: black, white, or tan.
"""
#cycle to the next state. 0 -> 1 -> 2 -> 0
self.state = (self.state + 1) % 3
bg, abg = colors[self.state]
self.core.config(bg=bg, activebackground=abg)
#print(self.location)
window = tk.Tk()
n = 9
board = []
for y in range(n):
row = [Tile(window, x, y) for x in range(n)]
board.append(row)
window.mainloop()
The problem is that core is a class variable which is created once and shared by all instances of class tile. It should be an instance variable for each tile instance.
Move core = Button(window, height = 2, width = 3, bg = "#F4C364") into tile.__init__() like this:
class Tile(object):
def __init__(self):
self.core = Button(window, height = 2, width = 3, bg = "#F4C364")
The root of the problem is that core is shared by all instances of the class by virtue of how you've defined it. You need to move creation of the button into the initializer.
I also suggest moving the configuration of the command into the button itself. The caller shouldn't need (nor care) how the button works internally. Personally I'd have the tile inherit from Button, but if you favor composition over inheritance I'll stick with that.
Example:
class tile(object):
def __init__(self):
self.core = Button(window, height = 2, width = 3, bg = "#F4C364"
command=self.cycle)

Crop Cairo-Generated PDF

I have the following script which generates a number of circles in a box on top of a bigger circle. The output is to a PDF, which I would like to be tightly bounded to the ink extents.
#!/usr/bin/env python
import math
import cairocffi as cairo
import random
def DrawFilledCircle(x,y,radius,rgba):
ctx.set_source_rgba(*rgba)
ctx.arc(x,y,radius,0,2*math.pi)
ctx.fill()
def DrawCircle(x,y,radius,rgba=(0,0,0,1)):
ctx.set_source_rgba(*rgba)
ctx.arc(x,y,radius,0,2*math.pi)
ctx.stroke()
surface = cairo.RecordingSurface(cairo.CONTENT_COLOR_ALPHA, None)
ctx = cairo.Context (surface)
DrawCircle(200,200,150,(0,0,0,1))
for i in range(1000):
DrawFilledCircle(200+(150-300*random.random()), 200+(150-300*random.random()), 4, (0,0,0,0.5))
#This part will change throughout the question
extents = surface.ink_extents()
pdfout = cairo.PDFSurface ("circle.pdf", extents[2], extents[3])
pdfctx = cairo.Context (pdfout)
pdfctx.set_source_surface(surface,0,0)
Running the script produces the following.
As you can see, the width and height are correct, but the origin needs to be shifted. Accordingly, I tried this:
pdfout = cairo.PDFSurface ("circle.pdf", extents[2], extents[3])
pdfctx = cairo.Context (pdfout)
pdfctx.set_source_surface(surface,extents[0],extents[1])
This just shifted things further to the bottom right.
That suggested using negative coordinates to shift things the other way:
pdfout = cairo.PDFSurface ("circle.pdf", extents[2], extents[3])
pdfctx = cairo.Context (pdfout)
pdfctx.set_source_surface(surface,-extents[0],-extents[1])
But that didn't work either:
As a back-up, I could make a shell call to pdfcrop, but that seems like a ridiculous workaround.
What can I do to achieve what I'm trying to do? Where am I going wrong? How can a lasting peace be achieved in Cairo?

Categories

Resources