0

在 PySimpleGUI 中使用 right_click_menu 时如何区分同一窗口中的多个元素?例如,使用下面的代码,我如何判断我尝试使用 right_click_menu 的两个 InputText 元素中的哪一个?如果我将某些内容复制到剪贴板,然后在其中一个输入字段上右键单击“粘贴”,则两个字段中将出现相同的数据。当我右键单击 InputText 字段之一时,如何编写代码来识别我在哪个字段上?:

import PySimpleGUI as sg

INPUT1 = 'INPUT1'
INPUT2 = 'INPUT2'

right_click_menu = ['',['Paste']]

layout = [
    [sg.Text('Input1'), sg.InputText('', key='INPUT1', right_click_menu = right_click_menu)],
    [sg.Text('Input2'), sg.InputText('', key='INPUT2', right_click_menu = right_click_menu)],
    [sg.Button(' OK '), sg.Button(' Exit ')]
    ]

window = sg.Window('Multiple Elements', layout)

input1:sg.InputText = window[INPUT1]
input2:sg.InputText = window[INPUT2]

while True:
    event, values = window.read()

    if event in (' Exit ', None):
        break

    if event == 'Paste':
        # How to tell whether I am right-clicking on INPUT1 or INPUT2?
        # With just one Input element, I could just do this: 

        input1.Widget.insert(sg.tk.INSERT, window.TKroot.clipboard_get())

        # What do I do when there is a second InputText field? 
        # Below won't work because I'll get the same text pasted into both fields.

        input2.Widget.insert(sg.tk.INSERT, window.TKroot.clipboard_get())



    if event == ' OK ':
        pass
        #Do blah

window.close()
4

1 回答 1

1

参考https://pysimplegui.readthedocs.io/en/latest/#keys-for-menus

::通过在菜单条目后添加一个键来表示一个键,然后是键。

import PySimpleGUI as sg

INPUT1 = 'INPUT1'
INPUT2 = 'INPUT2'

right_click_menu = [['',[f'Paste::Paste {i}']] for i in range(2)]

layout = [
    [sg.Text('Input1'), sg.InputText('', key='INPUT1', right_click_menu = right_click_menu[0])],
    [sg.Text('Input2'), sg.InputText('', key='INPUT2', right_click_menu = right_click_menu[1])],
    [sg.Button(' OK '), sg.Button(' Exit ')]
    ]

window = sg.Window('Multiple Elements', layout)

input1:sg.InputText = window[INPUT1]
input2:sg.InputText = window[INPUT2]

while True:
    event, values = window.read()

    if event in (' Exit ', None):
        break

    if event.startswith('Paste'):
        element = input1 if event.split()[1] == '0' else input2
        element.Widget.insert(sg.tk.INSERT, window.TKroot.clipboard_get())

window.close()
于 2021-10-01T04:45:49.670 回答