'Appending to a file based on changed amount not working (PySimpleGUI, Appending)
So I've written a code using PySimpleGui. While the code works as it is, it requires a special thing for a specific function, that doesn't make sense to me.
Put simply, this function in the code is supposed to store a value in a separate .py file (in this example code, stock.py) so that once the GUI is closed, reopened, etc. the value is remembered in the stock.py file, and called from the main code. The program has a lot of other functions, but this one is the one that seems to have an issue.
Inside the GUI the option to input text (an integer or will error) to add or subtract the number of items in stock is given, and this is where my problem lies. I have it written so I can just override the exact number I want to be items in stock, and the options to add or subtract a specific number from the stock. The override code works well, and as expected, but the add or subtract codes won't update the number in the stock.py file until the entire program (more than this function we're talking about) is closed and reopened. It will update locally (because I wrote it to do so) but if I close this separate function, but not the whole program, then reopen the function the updated value isn't there. And watching the stock.py file shows that when the call to append, and close is given, nothing is written in the file until the whole program is closed for some reason, which is the root of why reopening the function without reopening the whole program doesn't show the updated value.
So I'm going to add the whole While loop for this function of the add part. The subtract portion works the same way, just subtracting the inputted value, not adding.
Code for the GUI would be here###
window = sg.Window('Stock', layout)
stock = stock.stockamount #imported from the stock.py file earlier
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
if event == 'Add Stock':
try: ##ignore the try. the issue exists with or without the try/except.
addby = sg.popup_get_text('Input number to add below.')
updated = stock + int(addby)
window['-STOCK-'].Update(updated)
file = open("stock.py", "a")
file.write("\nstockamount = " + str(updated))
file.close()
The same code is used for subtracting amount, but updated = stock - int(subtract), and functions the same way. This code will locally update the '-STOCK-' value in the GUI with the correct number, but when you close this window, and then reopen it from the main window, the number isn't updated. It isn't until the whole program is closed, then reopened that the updated stockamount is both written into the stock.py file, and displayed in the GUI everytime it's reopened.
The code written below this is the override function, which basically the concept is just the input will be the number you want to change the value to, and this code is written pretty much the same way, and functions correctly, so I just don't understand why the addition and subtraction aspects of the above code don't save to the stock.py file instantly like this one below does:
#still in the same while loop in the same function#
if event == 'Override':
try: #again, ignore try for this example
overide = sg.popup_get_text('Type the amount of stock'))
window['-STOCK-'].Update(int(overide))
file = open("stock.py", "a")
file.write("\nstockamount= " + str(overide))
file.close()
So the root of the issue is that the first code (add) won't save the "stockamount = 1234" in stock.py until the entire program closes. but the second code (override) does, and functions how I want it to.
This is an issue just because the program is something that has many different functions, so switching around in them, instead of closing the whole program, the stock amount won't be updated until the entire program is closed if it's used with the add/subtract function. Only if you use the override function does it update to the stock.py file instantly, which I don't understand.
Thanks for any help! I just can't make sense of why one writes instantly and the other waits until the whole program is closed out.
**Editing here so to include a full simple example of the problem minus the rest of the (very long) program code. The issue is present in this code the same way it is in my example code above, and in my actual program. The folder of the file has stock.py and the main .py file, which I'm going to copy all of below. **
import PySimpleGUI as sg
import stock
def add_Stock(): #ignore the indent issue here, not present in code, just when copied.
form = sg.FlexForm('Stock')
stocknum = stock.stockamount
layout = [ [sg.Text("Below shows the amount of stock")],
[sg.Text(stocknum, key = '-STOCK-')],
[sg.Button('Add Stock'), sg.Button('Subtract Stock'), sg.Button('Override')] ]
window = sg.Window('Stock', layout)
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
if event == 'Add Stock':
try:
addby = sg.popup_get_text('Input number to add below.')
updated = stocknum + int(addby)
window['-STOCK-'].Update(updated)
file = open("stock.py", "a")
file.write("\nstockamount = " + str(updated))
file.close()
except:
sg.PopupError("There was a problem.")
elif event == 'Subtract Stock':
try:
addby = sg.popup_get_text('Input number to subtract below.')
updated = stocknum - int(addby)
window['-STOCK-'].Update(updated)
file = open("stock.py", "a")
file.write("\nstockamount = " + str(updated))
file.close()
except:
sg.PopupError("There was a problem.")
elif event == 'Override':
try:
overide = sg.popup_get_text('Type the amount of stock')
window['-STOCK-'].Update(int(overide))
file = open("stock.py", "a")
file.write("\nstockamount= " + str(overide))
file.close()
except:
sg.PopupError("There was a problem.")
window.close()
def main():#ignore the indent issue here, not present in code, just when copied.
form = sg.FlexForm('Startup')
layout = [ [sg.Button('View Stock'), sg.Button('Cancel')] ]
window = sg.Window('Startup', layout)
while True:
event, values = window.read()
if event == 'Cancel' or event == sg.WIN_CLOSED:
break
elif event == 'View Stock':
add_Stock()
window.close()
if __name__ == "__main__":#ignore the indent issue here, not present in code, just when copied.
main()
So again, to understand the issue. When you click 'View Stock' in the main window, then update by adding or subtracting stock, the value isn't saved into stock.py until main() and add_Stock() are totally closed out. So if stockamount = 5, I close the add_Stock() window after adding say 5 into the input, when I click "View Stock" in main again, it will only show "5" until I close the whole program, then reopen, click view stock again, where it will be "10". This issue shows because the "stockamount = #" doesn't get written into stock.py until the program closes for some reason.
Editing to add here that in my original project code "Override" does function as expected, but in this full test code, "Override" has the same problem that add/subtract have.
Solution 1:[1]
It will save to file immediately after you call method write and close.
You can check it by following code, button Write and Save to write one new line into file each time and button Update to read the full content of file.
import PySimpleGUI as sg
filename = 'test.txt'
with open(filename, 'wt') as f: # Make sure empty file
f.write('')
layout = [
[sg.Multiline('', size=(40, 10), key='Multiline')],
[sg.Button('Write and Save'), sg.Button('Update')],
]
window = sg.Window('Test', layout)
index = 1
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
elif event == 'Write and Save':
f = open(filename, 'a')
if index > 1:
f.write(f'\n')
f.write(f'Line {index}')
f.close()
index += 1
elif event == 'Update':
with open(filename, 'rt') as f:
text = f.read()
window['Multiline'].update(text)
window.close()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jason Yang |

