How can I automaticly read values on PySimpleGui? - python

I have added a browse folder button but it not gives me values until I click another button.
I tried reading it like this
while True:
event, values = mainwindow.Read()
if values['Select folder...'] != '':
print(values['Select folder...'])
but the same thing happened.

No layout shown in your issue.
For example, you use sg.FolderBrowse here.
The option target is default as (sg.ThisRow, -1), means element just before your sg.FolderBrowse at same row.
If there's no target in your layout, no event will be generated.
If there's target, event of target will be generated only when target with option enable_events=True.
So, you should have a target element in your layout, most of time, it is sg.InputText with option enable_events=True.
import PySimpleGUI as sg
layout = [
[sg.InputText(enable_events=True), sg.FolderBrowse('Select folder...')],
]
window = sg.Window("Title", layout, finalize=True)
while True:
event, values = window.read()
if event == sg.WINDOW_CLOSED:
break
print(event, values)
if values['Select folder...'] != '':
print(values['Select folder...'])
window.close()
0 {0: 'D:/Document', 'Select folder...': 'D:/Document'}
D:/Document
There'll be problem if any event generated from `sg.InputText`, like key 'A' pressed. That's not the event you need, and maybe neither element `sg.InputText`. So next example shown only `sg.FolderBrowse`.
import PySimpleGUI as sg
layout = [
[sg.InputText(disabled=True, visible=False, enable_events=True), sg.FolderBrowse('Select folder...')],
]
window = sg.Window("Title", layout, finalize=True)
while True:
event, values = window.read()
if event == sg.WINDOW_CLOSED:
break
print(event, values)
if values['Select folder...'] != '':
print(values['Select folder...'])
window.close()
0 {0: 'D:/Document', 'Select folder...': 'D:/Document'}
D:/Document

Related

pysimplegui Is there posible to add value to input and print it in windows

I would like to get value+2 in window after i input my number. i tried to to it that way but i dont understand how one variable is dic and str and diffrent time. Thats what i tried using pyspysimplegui example.
import PySimpleGUI as sg
layout = [
[sg.Text('x+2=:'), sg.Text(size=(15,1), key='-OUTPUT-')],
[sg.Input(key='-IN-')],
[sg.Button('Show'), sg.Button('Exit')]]
window = sg.Window('Pattern 2B', layout)
while True: # Event Loop
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Exit':
break
if event == 'Show':
print(type(event), values)
values += '2'
window['-OUTPUT-'].update(values['-IN-'])
window.close()
You got an event Show generated when you click on button Show, then window.read() in your while True event loop will return a 2-tuple, (event, values).
event is the event when window.read(), 'Show' here.
values is a dictionary with key:value of some elements, {'-IN-': ''} here.
The value of an Input element is in str, not int or number.
Refer Return Values
Revised code as
import PySimpleGUI as sg
layout = [
[sg.Text('x'), sg.Push(), sg.Input('', key='x')],
[sg.Text('x+2:'), sg.Push(), sg.Input('', disabled=True, key='x+2')],
[sg.Button('Show'), sg.Button('Exit')]]
window = sg.Window('Pattern 2B', layout)
while True: # Event Loop
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Exit':
break
elif event == 'Show':
x_string = values['x']
try:
x = int(x_string)
y = str(x + 2)
except ValueError:
y = "Wrong number !!!"
window['x+2'].update(value=y)
window.close()

Widget appears after the user's input

I'm creating a GUI and I had an issue. My GUI is going to interact with the users, so depending on the user's input I want a button to appear. How can I do it? Because so far I can only make the button appear once the window opens.
For example, on the image below I have a sg.InputText isolated, but what I realy want is that this widget appears only after the first sg.InputText is filled.
enter image description here
Create a Button element with option visible=False, update it with visible=True when the value of Input element not empty.
import PySimpleGUI as sg
layout = [
[sg.Image(data=sg.EMOJI_BASE64_HAPPY_JOY),
sg.Text("TRAINING PROGRAM"), sg.Push(),
sg.Button("Check", visible=False)],
[sg.Text("Pass the badge on the reader:"),
sg.Input('', enable_events=True, key='-INPUT-')],
]
window = sg.Window('Title', layout, finalize=True)
shown = False
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
elif event == '-INPUT-':
if values[event] != '':
if not shown:
shown = True
window['Check'].update(visible=True)
else:
shown = False
window['Check'].update(visible=False)
window.close()

Dynamically Updating an Element in a Multiple Window Setup

I have a quick question about updating fields dynamically in a multiple window setup such as the example above. I want it so that when the user selects autofill, values[SAVEINVENTORYPATH] is printed to the 'testinputtext' field in the settings window however when I use window.update, it searches for the keys in the main window rather than the settings window. How can I direct PySimpleGUI towards the settings window?
EDIT: Thank you for your help, I have edited the code and the autofill function works however currently, Autofill appears to freeze the window but I want people to be able to select Autofill and then hit Save and then the Settings window refreshes however I'm not sure where to currently place the while True loop. Thank you again for your assistance with this.
def create_settings_window(settings):
sg.theme('LightGrey6')
settings = load_settings(SETTINGS_FILE, DEFAULT_SETTINGS )
def TextLabel(text): return sg.Text(text+':', justification='r', size=(20,1))
layout = [ [sg.Text('Set Up Connection', font='Any 15')],
[TextLabel('Inventory List'), sg.Input(key='SAVEINVENTORYPATH'), sg.FileBrowse(key='INVENTORYLIST')],
[sg.Text(text='', key = 'testinputtext')],
[sg.Button('Save'), sg.Button('Autofill'), sg.Button('Exit')] ]
window = sg.Window('Settings', layout, keep_on_top=True, finalize=True,element_padding = (3,3.5))
test = window['testinputtext']
event, values = window.read()
if event == 'Autofill':
test.update(value = 'hi')
if event == 'Save':
save_settings(SETTINGS_FILE, settings, values)
sg.popup('Settings saved')
else:
print(event, values)
for key in SETTINGS_KEYS_TO_ELEMENT_KEYS:
try:
window[SETTINGS_KEYS_TO_ELEMENT_KEYS[key]].update(value=settings[key])
except Exception as e:
print(f'Problem updating PySimpleGUI window from settings. Key = {key}')
return window
def main():
window, settings = None, load_settings(SETTINGS_FILE, DEFAULT_SETTINGS )
while True: # Event Loop
#LAYOUT
if window is None:
settings = load_settings(SETTINGS_FILE, DEFAULT_SETTINGS )
sg.theme('LightGrey6')
layout = [[sg.Multiline(size=(180,10),key='Output',pad=(0,20))],
[sg.Button(button_text = 'Settings',key='Settings'),sg.Button(button_text = 'Load Output',key='LOAD_OUTPUT'),sg.Exit()]]
window = sg.Window('Settings Dynamic Update Test', layout, element_justification='center', size= (600,300))
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Exit':
break
window.close()
if event == 'Settings':
create_settings_window(settings)
else:
print(event, values)
window.close()
main()
It' better to handle each window in it's own event loop, mix windows together may get things mush difficult or complex.
Following example show the way to go.
import PySimpleGUI as sg
def popup():
sg.theme('DarkBlue4')
layout = [
[sg.Text("You name"), sg.Input("", key='Name')],
[sg.Text("", size=0, key='Test')],
[sg.Button('Save'), sg.Button('Auto Fill'), sg.Button('Cancel')],
]
window = sg.Window('Settings', layout, modal=True)
while True:
event, values = window.read()
if event in (sg.WIN_CLOSED, 'Cancel'):
flag = False
break
elif event == 'Save':
settings['Name'] = values['Name']
flag = True
break
elif event == 'Auto Fill':
window['Test'].update(values['Name'])
window.close()
return flag
def main_window():
sg.theme('DarkBlue3')
name = settings['Name']
value = name if name else 'None'
layout = [
[sg.Text("User Name:"), sg.Text(value, key='Name')],
[sg.Button('Settings'), sg.Button('Exit')],
]
return sg.Window('Main', layout)
settings = {'Name':None}
window = main_window()
while True:
event, values = window.read()
if event in (sg.WIN_CLOSED, 'Exit'):
break
elif event == 'Settings':
flag = popup()
if flag:
window.close()
window = main_window()
""" or just update element
name = settings['Name']
value = name if name else 'None'
window['Name'].update(value)
"""
window.close()

Value view/modification window

I'm working with plots and I want to call a PySimpleGUI window on a press of a TK button which will show my plot tuples and allow modifying them to later re-draw the plot. So far I took this cookbook example and added a save button:
layout += [[sg.Button('Save')]]
This is how I call it:
def readWindow(event):
values = window.read()
print(values)
editButton.on_clicked(readWindow)
and it successfully passes values when I click "save". But if I close the window and try to open it again, I get (None, None) in the console.
You don't need tkinter Button.
import PySimpleGUI as sg
# layout = ...
layout += [[sg.Button("Save", ...]]
window = sg.Window("Title", layout)
while True:
event, values = window.read()
if event == sg.WINDOW_CLOSED:
break
elif event == "Save":
print(event, values)
window.close()

PySimpleGUI make text selectable with mouse

I'm creating a textbox as follows:
sg.Text(size=(57, 10), background_color='white', text_color='red',
key='_console')
And it works fine, except the text isn't selectable!
I want the user to be able to copy the message to clipboard (by mouse selection and "copy").
How can it be done?
thx
According to the git hub issue related to this, the way to go about doing this is to create a read-only input and format it to look like the normal text elements:
https://github.com/PySimpleGUI/PySimpleGUI/issues/2928
import PySimpleGUI as sg
sg.theme('Dark Red')
layout = [ [sg.Text('My Window')],
[sg.InputText('You can select this text', use_readonly_for_disable=True, disabled=True, key='-IN-')],
[sg.Button('Go'), sg.Button('Exit')] ]
window = sg.Window('Window Title', layout, finalize=True)
window['-IN-'].Widget.config(readonlybackground=sg.theme_background_color())
window['-IN-'].Widget.config(borderwidth=0)
while True: # Event Loop
event, values = window.read()
print(event, values)
if event == sg.WIN_CLOSED or event == 'Exit':
break
window.close()

Categories

Resources