基于更改数量不起作用的文件附加到文件(Pysimplegui,附加)

发布于 2025-01-18 16:13:32 字数 4915 浏览 0 评论 0原文

所以我使用 PySimpleGui 编写了代码。虽然代码按原样工作,但它需要特定功能的特殊功能,这对我来说没有意义。

简而言之,代码中的此函数应该将值存储在单独的 .py 文件中(在本示例代码中为 stock.py),以便一旦 GUI 关闭、重新打开等,该值就会被记住在 stock 中。 py 文件,并从主代码中调用。该程序还有很多其他功能,但这个功能似乎有问题。

在 GUI 内部,给出了输入文本(整数或错误)来添加或减去库存商品数量的选项,这就是我的问题所在。我已经写好了它,这样我就可以覆盖我想要成为库存商品的确切数量,以及从库存中添加或减去特定数量的选项。覆盖代码运行良好,并且符合预期,但是加法或减法代码不会更新 stock.py 文件中的数字,直到整个程序(不仅仅是我们正在讨论的这个函数)关闭并重新打开。它将在本地更新(因为我编写它是为了这样做),但是如果我关闭这个单独的函数,而不是整个程序,然后重新打开该函数,则更新的值不存在。并且观察stock.py文件显示,当调用append和close时,文件中没有写入任何内容,直到整个程序因某种原因关闭,这就是为什么重新打开函数而不重新打开整个程序的根源不显示更新后的值。

因此,我将为添加部分的这个函数添加整个 While 循环。减法部分的工作方式相同,只是减去输入的值,而不是相加。

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()

相同的代码用于减去金额,但更新 = stock - int(subtract),并且功能相同。此代码将使用正确的数字在本地更新 GUI 中的“-STOCK-”值,但是当您关闭此窗口,然后从主窗口重新打开它时,该数字不会更新。直到整个程序关闭,然后重新打开,更新后的 stockamount 才会写入 stock.py 文件,并在每次重新打开时显示在 GUI 中。

下面编写的代码是覆盖函数,其基本上的概念只是输入将是您想要将值更改为的数字,并且此代码的​​编写方式几乎相同,并且功能正确,所以我只是不这样做不明白为什么上述代码的加法和减法方面不会像下面的代码那样立即保存到 stock.py 文件中:

#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()

所以问题的根源是第一个代码(add)不会保存“stockamount” = 1234" in stock.py 直到整个程序关闭。但第二个代码(覆盖)确实如此,并且按照我想要的方式运行。

这是一个问题,因为该程序具有许多不同的功能,因此在它们之间进行切换,而不是关闭整个程序,如果与 add/ 一起使用,则在关闭整个程序之前,库存量不会更新。减法函数。只有当您使用 override 函数时,它才会立即更新到 stock.py 文件,我不明白。

感谢您的帮助!我只是无法理解为什么一个人立即写入而另一个人等到整个程序结束。

**在这里进行编辑,以包含问题的完整简单示例,减去其余(很长)的程序代码。此代码中存在的问题与上面的示例代码和我的实际程序中的问题相同。该文件的文件夹包含 stock.py 和主 .py 文件,我将复制下面的所有内容。 **

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()

再次强调,要理解这个问题。当您在主窗口中单击“查看股票”,然后通过添加或减去股票进行更新时,该值不会保存到 stock.py 中,直到 main() 和 add_Stock() 完全关闭。因此,如果 stockamount = 5,我在输入中添加 5 后关闭 add_Stock() 窗口,当我再次单击 main 中的“查看股票”时,它只会显示“5”,直到我关闭整个程序,然后重新打开,单击再次查看库存,它将显示“10”。之所以出现此问题,是因为直到程序由于某种原因关闭后,“stockamount = #”才会写入 stock.py。

编辑以在此处添加,在我的原始项目代码中“Override”确实按预期运行,但在这个完整的测试代码中,“Override”具有与加/减相同的问题。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧时光的容颜 2025-01-25 16:13:32

调用方法写入并关闭后,它将立即保存。

您可以通过以下代码,按钮写入并保存将一行写入文件和按钮更新以读取文件的完整内容。

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()

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()

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文