Randy Murray
Randy Murray

Reputation: 79

PySimpleGUI get selected text

New to PySimpleGUI.

I have a multiline input box :

    layout1 = [[sg.Multiline(size=(45,5),key='-IN-')],...
    window1 = sg.Window('Source',layout1,finalize=True)
    event1,values1 = window1.read()

I type in some text and then using the mouse, I highlight a portion of the text. How do I get that selected (highlighted) text?

In Tkinter, I simply used :

        self.title = self.e.selection_get() 

but I like what I've seen of PySimpleGUI and would to try to stick with it.

I have searched here, github and google and haven't found anything about this. Hoping it is something simple and that someone is able to point me in the right direction.

Thanks,

Randy

Upvotes: 7

Views: 2923

Answers (2)

matan h
matan h

Reputation: 1148

I'm use tk.Entry withPySimpleGUI.Window.

import PySimpleGUI as sg

layout1 = [[sg.Multiline(size=(45, 5), key='-IN-')], [sg.OK(key="-ok-")]]
window1 = sg.Window('Source', layout1, finalize=True)

while 1:
    event1, values1 = window1.read()
    print(event1)
    if event1 == sg.WIN_CLOSED:
        break
    elif event1 == "-ok-":
        try:
            title = window1["-IN-"].Widget.selection_get()
        except sg.tk.TclError:
            title = None
        print("selected text:", title)

Upvotes: 0

Mike from PSG
Mike from PSG

Reputation: 5754

In the PySimpleGUI documentation, you'll find a section on "Extending PySimpleGUI". It discusses how to go about using features of tkinter that are not yet implemented in PySimpleGUI.

Each element has a member variable named Widget. This variable contains the underlying widget used in your layout. This variable is your gateway to the tkinter features not yet implemented in PySimpleGUI. It makes extending PySimpleGUI really straighforward.

This is your code with additional code using the Widget variable.

import PySimpleGUI as sg

layout1 = [[sg.Multiline(size=(45, 5), key='-IN-')], [sg.OK(key="-ok-")]]
window1 = sg.Window('Source', layout1, finalize=True)

while True:  # Event Loop
    event, values = window1.read()
    selection = window1['-IN-'].Widget.selection_get()
    print('selection = ', selection)

The important part to pick up from this answer is that all elements have this member variable that can be used to extend PySimpleGUI. This is the most important part of the code:

window1['-IN-'].Widget

It looks up the element based on the key, then gives you the tkinter widget that implements it. At this point, you can make all of the calls that are normally available to you using that widget.

Upvotes: 4

Related Questions