需要在Linux上的Python中将键盘焦点保持在OpenCV窗口上

zysjyyx4  于 2023-03-01  发布在  Linux
关注(0)|答案(1)|浏览(188)

我在Python代码中打开多个窗口,需要OpenCV窗口来保持键盘焦点。我可以在Windows操作系统上做到这一点,我认为OS-X会自动做到这一点,因为其他窗口不能接受按键,但我需要Linux上的帮助。我相信我在代码中注解掉了正确的语句,以保持窗口活动。但是我需要从OpenCV窗口名'cv 2 window'中获取窗口句柄(QWidget.window())。下面是一个示例代码,如果window_focus("cv2window")没有注解掉,它将保持焦点。我只需要完成Linux版本的工作。

import sys
    import cv2
    import numpy as np
    import matplotlib as mpl
    import PyQt6 as qt  # Must be before import of matplotlibl.pyplot
    mpl.use('qtagg')    # Use the QT backend
    import matplotlib.pyplot as plt
    
    if sys.platform == "win32":
        import warnings
        warnings.simplefilter("ignore", UserWarning )  # Fix Windows warning
        sys.coinit_flags = 2
        from pywinauto.findwindows import find_window    # Windows OS window focus
        import win32gui
    #elif sys.platform == "darwin":
        #import AppKit    # pip install pyobjc       Mac OS window focus
    elif "linux" in sys.platform:
        print( "Linux support in development" )
    
    def window_focus( window_name ):
        if sys.platform == "win32":
            win32gui.SetForegroundWindow(find_window(title=window_name))
        #elif sys.platform == "darwin":    # OSX doesn't seem to need this to maintain focus
            #cv2.setWindowProperty(window_name, cv2.WND_PROP_TOPMOST, 1)
            #AppKit.NSApplication.sharedApplication().activateIgnoringOtherApps_(1)
        elif "linux" in sys.platform:
            print( "Linux support in development" )
            #qt.QtWidgets.QMainWindow.setWindowState( 0, qt.QtCore.Qt.WindowActive )
            # Error says first arg must be QWidget type so still need window handle
    
    img = cv2.imread( "python_colors.png" )
    t = np.arange( 0.0, 2.0, 0.01 )
    s = np.sin( 2 * np.pi * t )
    fig = plt.figure( "MatPlotLibWindow" )
    plt.plot( t, s )
    plt.ion()
    plt.show()
    
    while True:
    
        cv2.imshow( "cv2window", img )
    
        plt.plot( t, s )
        plt.show()
    
        window_focus( "cv2window" )
    
        while True:
            k = cv2.waitKey(0)
            if k != -1:    # Wait for any key press
                break
        if k == ord('x'):
            break

这适用于OS-X和Windows,但还不适用于Linux。

g52tjvyc

g52tjvyc1#

所以我认为你可以通过使用pynput模块或任何其他模块,让你得到键盘按键集中输入。你正在寻找的术语是“热键”。据我所知,热键工作,即使窗口是在背景或没有突出显示。如果我分配一个热键,它基本上响应按键,即使你不在该窗口。

相关问题