如何使用快捷键快速切换显示器方向?

在查看之前是否有人问过这个问题时,我在Windows上找到了这个问题。

我想在Linux / Ubuntu上做类似的事情(快捷方式或终端别名/命令),以便能够在横向和纵向模式之间快速切换外部显示器,而不必转到显示器设置它并确认配置。

Jacob Vlijm提供了一个有效的Python脚本 。 如果你有另一个想法,我很想知道它。

更新 :我已更新Jacob的脚本, 如果它们已连接,则可用于两个屏幕 。

下面的脚本是切换任一屏幕的旋转:

#!/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]) 

如何使用

  1. 将脚本复制到空文件中,将其另存为toggle-rotate.py
  2. 在脚本的head部分中,设置:

    • 您要切换的屏幕名称(通过在终端中运行命令xrandr查找)
    • 旋转方向, leftright (在引号之间,如示例中所示)。

       # --- set the name of the screen and the rotate direction below screen = "VGA-1" rotate = "left" # --- 
  3. 测试 – 通过命令运行它(两次,从终端):

     python3 /path/to/toggle-rotate.py 
  4. 如果一切正常,请将其添加到快捷键。 选择:系统设置>“键盘”>“快捷方式”>“自定义快捷方式”。 单击“+”并添加命令:

     python3 /path/to/toggle-rotate.py 

    到你选择的捷径……

而已。

说明

在命令xrandr的输出中,屏幕的当前旋转(如果有的话)直接在屏幕位置后提到,例如:

 VGA-1 connected 1024x1280+1680+0 left (normal left inverted right x axis y axis) 376mm x 301mm 

在示例中,我们看到: 1024x1280+1680+0 left 。 该脚本会查看与脚本头部中提到的屏幕相对应的行。 如果屏幕旋转,脚本将运行( xrandr )命令:

 xrandr --output  --rotate normal 

如果没有 ,它运行(例如):

 xrandr --output  --rotate left 

逆时针旋转屏幕

我一直在使用雅各布的剧本。 但是我现在正在使用适配器,所以我希望能够切换方向,无论显示器是连接到HDMI还是通过适配器。 为此,我修改了Javob的脚本并借用了他写的另一个函数 :

 import subprocess def screens(): ''' get connected screens ''' output = [l for l in subprocess.check_output(["xrandr"]).decode("utf-8").splitlines()] return [l.split()[0] for l in output if " connected " in l] # --- set the name of the screen and the rotate direction below # screen = "HDMI-1" # run "xrandr" to get the screen rotate = "left" # the desired orientation if "HDMI-1" in screens(): screen = "HDMI-1" elif "DP-1" in screens(): screen = "DP-1" else: pass # --- # only run if screen is declared (ie either HDMI-1 or DP-1 are connected) if screen: 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])