使用python gui

时间:2018-07-18 22:04:16

标签: python

我正在尝试构建一个轻量级的Text-to-Speech GUI,可以在其中选择Word或Chrome中的文本,然后在GUI中按一个按钮并读取它。

我已经弄清楚了创建GUI并使TTS正常工作的所有步骤,但是我无法获得合适的外形尺寸。我试图模仿Dragon Naturally Speaking的文字转语音的外形,因为它很简单,而且我习惯了。

以下是我无法使用的用户故事中缺少的步骤,按顺序:

1)用户使用鼠标突出显示应用程序中的文本(单词,chrome,记事本等),然后按gui按钮

2)来自外部应用程序的数据以UTF-8的形式提取并存储在名为“文本”的变量中

我知道有一个问题,就是几个窗口可以选择文本。我的解决方案是从最近选择的窗口中提取选择的文本。

现在,解决问题的方法是使用Ctrl-C组合键,无论我要阅读什么文本,然后按一下按钮,因为我可以从剪贴板中提取数据,但这确实是一种非常糟糕的用户体验,而且令人困惑。我尝试使用pyperclip来获取将文本放入剪贴板的按钮,但是它似乎不起作用,因此我不确定剪贴板的想法是否是死路一条。

def select_text(self):
    #copy
    pyperclip.copy() # doesn't work        

    #get text
    win32clipboard.OpenClipboard()
    text = win32clipboard.GetClipboardData()
    win32clipboard.CloseClipboard()

    #say it!
    self.say_text(text)

我似乎在任何地方都找不到这样的东西,而且我也不知道从哪里开始。任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:0)

我想我明白了。这很丑陋,但是有效。我是编码的初学者,这对我来说只是一种爱好。老实说,我很高兴它能正常工作。

我已将命令绑定到Alt_L + Q;稍后我可能会添加Alt_R + Q,但是我永远不会使用它们。由于某些原因,单独使用没有L或R的Alt无效。

此外,如果没有第一个sleep语句,它将根本无法工作。第二个睡眠声明是预防性的。

# set clipboard data
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText('No text is currently selected.')
win32clipboard.CloseClipboard()

text = None #this is what will be read
chg_rate = 0 #reading speed +/- 0.0 to 1.0
chg_vol = 0 #volume +/- 0.0 to 1.0

def get_text():
    #current_window = win32gui.GetForegroundWindow()
    import pythoncom
    pythoncom.CoInitialize()
    cw = win32com.client.Dispatch('WScript.Shell')
    time.sleep(.7)
    cw.SendKeys('^c') #copies text
    time.sleep(.2)

    #get text
    win32clipboard.OpenClipboard()
    text = win32clipboard.GetClipboardData()
    win32clipboard.CloseClipboard()

    return text


#define the hot key
def create_hotkey():
    # The key combination to check
    COMBINATIONS = [
        {keyboard.Key.alt_l, keyboard.KeyCode(char='Q')},
        {keyboard.Key.alt_l, keyboard.KeyCode(char='q')}
    ]

    # The currently active modifiers
    current = set()

    def execute():
            text = get_text()
            if not isinstance(text, str):
                text = "Selected input is not UTF-8 text."
            say_text(text)

    def on_press(key):
        if any([key in COMBO for COMBO in COMBINATIONS]):
            current.add(key)
            if any(all(k in current for k in COMBO) for COMBO in COMBINATIONS):
                execute()

    def on_release(key):
        if any([key in COMBO for COMBO in COMBINATIONS]):
            current.remove(key)

    with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()

#run hotkey
create_hotkey()
相关问题