Moved clipboard operations to a single function to make event loop cleaner

This commit is contained in:
PySimpleGUI 2021-06-06 10:31:54 -04:00
parent f2f0ea99a7
commit 6e7d267583
1 changed files with 29 additions and 20 deletions

View File

@ -25,6 +25,29 @@ import PySimpleGUI as sg
right_click_menu = ['', ['Copy', 'Paste', 'Select All', 'Cut']] right_click_menu = ['', ['Copy', 'Paste', 'Select All', 'Cut']]
MLINE_KEY = '-MLINE-' MLINE_KEY = '-MLINE-'
def do_clipboard_operation(event, window, element):
if event == 'Select All':
element.Widget.selection_clear()
element.Widget.tag_add('sel', '1.0', 'end')
elif event == 'Copy':
try:
text = element.Widget.selection_get()
window.TKroot.clipboard_clear()
window.TKroot.clipboard_append(text)
except:
print('Nothing selected')
elif event == 'Paste':
element.Widget.insert(sg.tk.INSERT, window.TKroot.clipboard_get())
elif event == 'Cut':
try:
text = element.Widget.selection_get()
window.TKroot.clipboard_clear()
window.TKroot.clipboard_append(text)
element.update('')
except:
print('Nothing selected')
def main():
layout = [ [sg.Text('Using a custom right click menu with Multiline Element')], layout = [ [sg.Text('Using a custom right click menu with Multiline Element')],
[sg.Multiline(size=(60,20), key=MLINE_KEY, right_click_menu=right_click_menu)], [sg.Multiline(size=(60,20), key=MLINE_KEY, right_click_menu=right_click_menu)],
[sg.B('Go'), sg.B('Exit')]] [sg.B('Go'), sg.B('Exit')]]
@ -35,28 +58,14 @@ mline:sg.Multiline = window[MLINE_KEY]
while True: while True:
event, values = window.read() # type: (str, dict) event, values = window.read() # type: (str, dict)
print(event, values)
if event in (sg.WIN_CLOSED, 'Exit'): if event in (sg.WIN_CLOSED, 'Exit'):
break break
if event == 'Select All':
mline.Widget.selection_clear() # if event is a right click menu for the multiline, then handle the event in func
mline.Widget.tag_add('sel', '1.0', 'end') if event in right_click_menu[1]:
elif event == 'Copy': do_clipboard_operation(event, window, mline)
try:
text = mline.Widget.selection_get()
window.TKroot.clipboard_clear()
window.TKroot.clipboard_append(text)
except:
print('Nothing selected')
elif event == 'Paste':
mline.Widget.insert(sg.tk.INSERT, window.TKroot.clipboard_get())
elif event == 'Cut':
try:
text = mline.Widget.selection_get()
window.TKroot.clipboard_clear()
window.TKroot.clipboard_append(text)
mline.update('')
except:
print('Nothing selected')
window.close() window.close()
if __name__ == '__main__':
main()