
本文将指导你如何在使用 PySimpleGUI 创建密码验证窗口时,避免常见的 "You have tried 100 times to read a closed window" 错误。我们将详细讲解错误原因,并提供正确的代码示例,确保你的程序能够稳定运行,并返回到主窗口。
在使用 PySimpleGUI 创建模态窗口(例如密码验证窗口)时,需要特别注意窗口的生命周期管理,尤其是在循环中读取窗口事件时。如果窗口在循环内部被关闭,但循环没有正确退出,程序会持续尝试从已关闭的窗口读取数据,从而导致 "You have tried 100 times to read a closed window" 错误。
错误原因分析
该错误通常发生在以下场景:
要解决这个问题,关键在于确保在窗口关闭后,立即退出 while 循环。以下是修正后的代码示例:
import PySimpleGUI as sg
import hashlib
def protect():
layout = [
[sg.Text('Въведете парола:', size=(20, 1)), sg.InputText('', key='-PASSWORD-', password_char='*', size=(20, 1))],
[sg.Button("Confirm"),sg.Button("Delete")]
]
password_window = sg.Window('Функция изискваща достъп на управител', layout, modal=True)
def verify_password(password):
hash = '112e3f234c4d002cewc328e0be632rf34fer7181csf940b25c79d7bttrh3598ce12'
password_utf = password.encode('utf-8')
password_hash = hashlib.sha256(password_utf).hexdigest()
print(password_hash)
if hash == password_hash:
return True
return False
while True:
event, values = password_window.read()
if event == "Delete" or event == sg.WIN_CLOSED:
break # 关键:退出循环
if event == 'Confirm':
password_input_value = values['-PASSWORD-']
if verify_password(password_input_value):
break # 关键:退出循环
else:
continue
password_window.close() # 确保在循环结束后关闭窗口
# protect() # 示例调用,可以移除,根据你的主程序逻辑调用 protect() 函数。代码解释
注意事项
总结
通过在关闭窗口后立即退出循环,并确保在循环结束后才关闭窗口,可以有效避免 PySimpleGUI 中 "You have tried 100 times to read a closed window" 错误。 记住,良好的窗口生命周期管理是编写稳定 PySimpleGUI 应用程序的关键。
以上就是使用 PySimpleGUI 实现密码验证功能:避免“读取已关闭窗口”错误的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号