PySimpleGUI / PySimpleGUI

Python GUIs for Humans! PySimpleGUI is the top-rated Python application development environment. Launched in 2018 and actively developed, maintained, and supported in 2024. Transforms tkinter, Qt, WxPython, and Remi into a simple, intuitive, and fun experience for both hobbyists and expert users.

Home Page:https://www.PySimpleGUI.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[ Question] 1- add input and 2 -Ignore blank text input

mmiesner opened this issue · comments

Type of Issue (Enhancement, Error, Bug, Question)

Hello,
I have two questions that I cannot seemingly find the answer to.
First, I'd like to be able to click a button (such as "+add") and PSG will add a second input box- which will then call a certain function twice instead of once.

Second, if an input is empty, currently, my program will quit . How do I go about it essentially ignoring empty inputs?
This comes from a spot where ideally I can input a text document into a specific part of my program. When I choose not to do this, I'd like it to proceed on rather than quitting.

Here is the output:
blocktext = open(values["input_BKGRD-KEY-"],encoding="utf8", errors='ignore')
FileNotFoundError: [Errno 2] No such file or directory: ''


Operating System

Linux

PySimpleGUI Port (tkinter, Qt, Wx, Web)

tkinter


Versions

Version information can be obtained by calling sg.main_get_debug_data()
Or you can print each version shown in ()

Python version (sg.sys.version)

3.8

PySimpleGUI Version (sg.__version__)

4.45.0

GUI Version (tkinter (sg.tclversion_detailed), PySide2, WxPython, Remi)


Your Experience In Months or Years (optional)

Years Python programming experience
hobby for one year, very little time to do it

Years Programming experience overall
1

Have used another Python GUI Framework? (tkinter, Qt, etc) (yes/no is fine)
none

Anything else you think would be helpful?


Troubleshooting

These items may solve your problem. Please check those you've done by changing - [ ] to - [X]

  • [X ] Searched main docs for your problem www.PySimpleGUI.org
  • [ X] Looked for Demo Programs that are similar to your goal Demos.PySimpleGUI.org
  • If not tkinter - looked for Demo Programs for specific port
  • For non tkinter - Looked at readme for your specific port if not PySimpleGUI (Qt, WX, Remi)
  • [X ] Run your program outside of your debugger (from a command line) - I have done this, but I dont think this related to the issue. I think this is about my knowledge base.
  • Searched through Issues (open and closed) to see if already reported Issues.PySimpleGUI.org
  • Tried using the PySimpleGUI.py file on GitHub. Your problem may have already been fixed but not released

Detailed Description

Code To Duplicate

A short program that isolates and demonstrates the problem (Do not paste your massive program, but instead 10-20 lines that clearly show the problem)

This pre-formatted code block is all set for you to paste in your bit of code:

# Paste your code here

#start text insertion code (background text)
        blocktext = open(values["input_BKGRD-KEY-"],encoding="utf8", errors='ignore')
        bkgdata = blocktext.read()
        blocktext.close()

Screenshot, Sketch, or Drawing

Psyhchpile


Watcha Makin?

If you care to share something about your project, it would be awesome to hear what you're building.
My program is now (lol) in version 1.3!
It works, and has worked with and without a GUI- and I use it regularly to generate a draft of my work-- but I want to add to the program.
The program takes 3 template documents and creates filled in templates for psychological evaluations for me. It uses find and replace primarily to allow me to do my work in batches instead of individually.

There're lot of different situations for your case, I cannot figure out your exact requirements.

Here's a simple demo to open a text file.

from pathlib import Path
import PySimpleGUI as sg

layout = [
    [sg.Input('', key="-INPUT-"), sg.FileBrowse(file_types=(("All TXT Files", "*.txt"), ("All Files", "*.*")))],
    [sg.Multiline('', size=(40, 10), expand_x=True, key='-MULTILINE-')],
    [sg.Text("", expand_x=True, key='-STATUS-'), sg.Button('Submit')],
]
window = sg.Window("PsychPile 1.3.0", layout)

while True:

    event, values = window.read()

    if event == sg.WIN_CLOSED:
        break

    elif event == 'Submit':
        filename = values["-INPUT-"].strip()
        if filename and Path(filename).is_file():
            window['-STATUS-'].update('')
            with open(filename, mode='rt', encoding="utf8", errors='ignore') as f:
                data = f.read()
            window['-MULTILINE-'].update(data)
        else:
            window['-STATUS-'].update('File not exist !!!')

window.close()

image

Thanks for responding!
this will allow the program to move forward if I dont put anything in that background/ testing file boxes?
Currently it works as long as I select documents, but I dont always want to do that.

@jason990420 Your example is interesting for the PySimpleGUI newbie that I am. Question: what is the link between Input and FileBrowse that allows the latter to inject its result to Input?

@macdeport

Question: what is the link between Input and FileBrowse that allows the latter to inject its result to Input?

Find the option target in Button element or "Chooser" Button in Button Element

this will allow the program to move forward if I dont put anything in that background/ testing file boxes?
Currently it works as long as I select documents, but I dont always want to do that.

Sorry, it cannot help me to figure out what the requirement is.

@jason990420

Find the option target in Button element or "Chooser" Button in Button Element

This is of course fundamental and I am unaware of it ( pros/cons of default options) thanks for this leap forward.

this will allow the program to move forward if I dont put anything in that background/ testing file boxes?
Currently it works as long as I select documents, but I dont always want to do that.

Sorry, it cannot help me to figure out what the requirement is.

Hi Jason,
Let me try to clarify it. I know my wording was weird.
If you look at the GUI picture above, there are two boxes with browse buttons (background and testing).
If I do not choose a text file to insert, the program returns an error and does not complete.

The errror it returns is:
blocktext = open(values["input_BKGRD-KEY-"],encoding="utf8", errors='ignore')
FileNotFoundError: [Errno 2] No such file or directory: ''

I want to be able to pass over these (not choose files to insert) and the program still be able to execute.

This is probably the biggest hurdle I currently have.
The other issue can wait.

I want to be able to pass over these (not choose files to insert) and the program still be able to execute.

The code in my previous reply, Button Send still be able to execute if not choose file to insert, work as you said

I likely haven't absorbed enough here to provide exactly what's needed, but do want to share my philosophy of "Chooser Buttons". mike's philosophy on "chooser buttons":

I don't like them

Instead, I want the user's code to do the work of getting information and filling in elements, etc. It gives users more freedom and it removes complexity from PySimpleGUI.

import PySimpleGUI as sg

layout = [  [sg.Text('My Non-Chooser Browser Button')],
            [sg.Input(key='-FILE-'), sg.Button('Browse')],
            [sg.Button('Exit')]  ]

window = sg.Window('The No-Chooser Solution', layout)

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event == 'Exit':
        break
    elif event == 'Browse':
        filename = sg.popup_get_file('This string not seen', no_window=True)    # open file dialog
        if filename is not None:                    # fill Input Element with the filename
            window['-FILE-'].update(filename)

window.close()

Browse Example

Jason,
Can you help me learn so I can continue working?
BTW, thanks so much for your help thus far.

I'm not sure what I need to do with these lines of code:

window['-MULTILINE-'].update(data)
else:
window['-STATUS-'].update('File not exist !!!')

When I run that code, I get this error:
blocktext = open(values["input_BKGRD-KEY-"],encoding="utf8", errors='ignore')
FileNotFoundError: [Errno 2] No such file or directory: ''

Print out what file you're trying to open. This isn't a PySimpleGUI error... it's a basic Python "File not found".

Print the values dictionary since you're trying to open something from that dictionary and see what the value of it is.

Code with comment for the event loop.

while True:

    event, values = window.read()

    if event == sg.WIN_CLOSED:
        break

    elif event == 'Submit':
        filename = values["-INPUT-"].strip()
        if filename and Path(filename).is_file():           # if filename is not empty and file exist
            window['-STATUS-'].update('')                   # Clear any message in Text element which with key '-STATUS-'
            with open(filename, mode='rt', encoding="utf8", errors='ignore') as f:
                data = f.read()
            window['-MULTILINE-'].update(data)              # Update '-MULTILINE-' element with the data read from file
        else:
            window['-STATUS-'].update('File not exist !!!') # If filename is empty or file not exist, show the message in '-STATUS-' element

window.close()

When I run that code, I get this error:
blocktext = open(values["input_BKGRD-KEY-"],encoding="utf8", errors='ignore')
FileNotFoundError: [Errno 2] No such file or directory: ''

It mean that you didn't check the filename from your Input element if it is not empty and file exist, before you open it.

Thanks so much.
So when I put in sample text files, it throws the error:

line 204, in
if filename and Path(filename).is_file():
NameError: name 'Path' is not defined

When I skip over it (as I want to be able to do) and not select any files for the background and testing sections, I get:

Traceback (most recent call last):
File V1.3.GUI.py", line 231, in
blocktext = open(values["input_BKGRD-KEY-"],encoding="utf8", errors='ignore')
FileNotFoundError: [Errno 2] No such file or directory: ''

So I guess I dont understand what you mean "check the filename from your input element" because as I'm thinking about this.. there is no filename, because I skipped over it.

I must be misunderstanding something seemingly basic.

Path - This class represents concrete paths of the system’s path flavour and import from library pathlib.
You will get exception NameError: name 'Path' is not defined if you don't import pathlib library.

You may miss the first statement in my code.

from pathlib import Path

In following statements,

filename = values["-INPUT-"].strip()
if filename and Path(filename).is_file():

It means

  • filename will be True if the filename, the content of "-INPUT-" Input element, is not empty here.
  • Path(filename).is_file() will be True if the path points to a regular file (or a symbolic link pointing to a regular file).

This file exist and can open this file to read only when both of those two conditions met, else file not exist.
It is necessary to check the string for the path of file if it is an existing file or not before you open this file, or you will get exception if wrong path.

Thank you, this solved my problem.
I now have another issue, but this specific issue can be resolved and I'll work on the other one on my own.

I really appreciate your help AND for instructing me about Path.

Thanks for the 'thanks" @mmiesner! It's really awesome to have Jason's help on the project. It's always nice to see users appreciate his help too. I dunno, maybe it's silly to some, but sometimes it's the little things that can have biggest impacts. A simple "thank you" goes a long ways.