How can I quickly toggle monitor orientation with a shortcut key?
While looking if someone asked this question before, I landed on this for Windows.
I'd like to do something similar (shortcut or terminal alias/command) on Linux/Ubuntu to be able to quickly switch the external monitor between landscape and portrait mode instead of having to go to Displays setting it and confirming the configuration.
Jacob Vlijm provided a Python script which works. If you have another idea I'd love to know about it.
Update: I have updated Jacob's script to work for two screens if they are connected.
The script below is to toggle rotation of either one of your screens:
#!/usr/bin/env python3
import subprocess
# --- set the name of the screen and the rotate direction below
screen = "VGA-1"
rotate = "left"
# ---
matchline = [
l.split() for l in subprocess.check_output(["xrandr"]).decode("utf-8").splitlines()\
if l.startswith(screen)
][0]
s = matchline[
matchline.index([s for s in matchline if s.count("+") == 2][0])+1
]
rotate = "normal" if s == rotate else rotate
subprocess.call(["xrandr", "--output", screen, "--rotate", rotate])
How to use
- Copy the script into an empty file, save it as
toggle-rotate.py
-
In the head section of the script, set:
- the name of the screen you'd like to toggle (find out by running in a terminal the command
xrandr
) -
the rotate direction, either
left
orright
(between quotes, like in the example).# --- set the name of the screen and the rotate direction below screen = "VGA-1" rotate = "left" # ---
- the name of the screen you'd like to toggle (find out by running in a terminal the command
-
Test- run it by the command (two times, from a terminal):
python3 /path/to/toggle-rotate.py
-
If all works fine, add it to a shortcut key. Choose: System Settings > "Keyboard" > "Shortcuts" > "Custom Shortcuts". Click the "+" and add the command:
python3 /path/to/toggle-rotate.py
to a shortcut of your choice...
That's it.
Explanation
In the output of the command xrandr
, the current rotation of your screen (if any) is mentioned directly after the screen's position, for example:
VGA-1 connected 1024x1280+1680+0 left (normal left inverted right x axis y axis) 376mm x 301mm
In the example, we see: 1024x1280+1680+0 left
. The script looks into the line, corresponding to the screen, mentioned in the head of the script. if the screen is rotated, the script runs the (xrandr
) command:
xrandr --output <screen_name> --rotate normal
if not, it runs (for example):
xrandr --output <screen_name> --rotate left
To rotate the screen counter-clockwise