Ubuntu – How to make a keyboard shortcut to turn off and turn on the screen?


I changed my laptop from a Lenovo U310 to a Dell Inspiron 7537. The Lenovo had a special key for turning off and on the screen, but the Dell doesn't have it. I want to know if there is a command for turning off and on the screen by using the same keyboard shortcut (something like CTRL+A, or similar).

Best Answer

  • There are two circumstances that make your situation a bit different from the supposed duplicate(s):

    1. Some process seems to wake your screen up, if your screen wakes up after the xset dpms force off command, it must be. My screen doesn't for example.
    2. If you don't want your screen to wake up, just with any key press, the xset dpms force off command is not doing what you want.

    A workaround is the script below. What it does:

    • It looks up your screen's name and the current brightness
    • if the brightness is not equal to zero, it blacks the screen, else it sets brightness to normal

    In other words: It toggles between black screen and normal brightness.

    How to use

    • Copy the script into an empty file, save it as toggle_screen.py

    • Run it by the command:

        python3 /path/to/toggle_screen.py
    • Make sure you can repeat the command with a black screen, or else you will have to log out to toggle back...

    • If it works as you'd like it to, add it to a keyboard shortcut: Choose: System Settings > "Keyboard" > "Shortcuts" > "Custom Shortcuts". Click the "+" and add the command.

    The script

    #!/usr/bin/env python3
    import subprocess
    cmd1 = "xrandr --verbose"
    get = subprocess.check_output(["/bin/bash", "-c", cmd1]).decode("utf-8").split()
    brightness = get[get.index("Brightness:")+1]
    screens = [get[i-1] for i in range(len(get)) if get[i] == "connected"]
    if brightness == "1.0":
        for scr in screens:
            subprocess.Popen(["/bin/bash", "-c", "xrandr --output "+scr+" --brightness 0"])
        for scr in screens:
            subprocess.Popen(["/bin/bash", "-c", "xrandr --output "+scr+" --brightness 1"])