PySimpleGUI: _tkinter.TclError: invalid command name ".!toplevel.!frame3.!entry"

PySimpleGUI: _tkinter.TclError: invalid command name ".!toplevel.!frame3.!entry"

我正在尝试更新 PySimpleGUI 输入文本字段。这是我的代码:

import PySimpleGUI as sg
layout=[
[sg.InputText('',key='-IN-')],
[sg.InputText('',readonly='true',key='-RESULT-')]
]
win=sg.Window('Test',layout)
while True:
    event,values=win.Read()
    win['-RESULT-'].update(win['-IN-'].get())

但是我得到这样的错误:

Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/temp_iiec_codefile.py", line 9, in <module>
    win['-RESULT-'].update(win['-IN-'].get())
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/PySimpleGUI/PySimpleGUI.py", line 1666, in update
    self.TKEntry.icursor(tk.END)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/tkinter/__init__.py", line 3057, in icursor
    self.tk.call(self._w, 'icursor', index)
_tkinter.TclError: invalid command name ".!toplevel.!frame2.!entry"

我们可以发现只有一个事件是window的关闭按钮被点击。 单击window的关闭按钮后,window将被销毁,您无法对window进行任何操作,因此您需要检查window是否关闭并从while循环中跳出关闭 window.

您可以设置 sg.Input 的选项 enable_events=True 以启用输入时生成的事件。

import PySimpleGUI as sg

layout = [
    [sg.InputText('', enable_events=True, key='-IN-')],
    [sg.InputText('', readonly=True, key='-RESULT-')]
]
win = sg.Window('Test',layout)

while True:

    event, values = win.read()

    if event == sg.WINDOW_CLOSED:
        break
    elif event == '-IN-':
        # win['-RESULT-'].update(win['-IN-'].get())
        text = values['-IN-']
        win['-RESULT-'].update(text)

win.close()