如何在PySimpleGUI中使用Yes/No弹窗?求清晰实现指引
PySimpleGUI Yes/No弹窗正确使用指南
你的代码逻辑框架没问题,但判断条件的字符串大小写错误——PySimpleGUI的popup_yes_no()返回值是大写开头的"Yes"(点击「是」)和"No"(点击「否」),而非全小写的"yes"/"no",这会导致你的分支判断无法触发预期逻辑。
修正后的完整代码
import PySimpleGUI as sg import time sg.popup("Welcome to this random file.") result = sg.popup_yes_no("Would you like to continue?") if result == "Yes": sg.popup("Great! You have chosen to continue the process.") elif result == "No": sg.popup("Exiting process...") sg.popup("See you!") time.sleep(3) exit() else: sg.popup("Invalid input")
关键使用要点
- 返回值规则:
popup_yes_no()仅返回三种值:点击「是」返回"Yes",点击「否」返回"No",关闭弹窗(右上角叉号)返回None。 - 用常量避免大小写错误:PySimpleGUI提供了内置常量替代硬编码字符串,可读性和容错性更强:
if result == sg.POPUP_YES_NO_YES: # 处理确认逻辑 elif result == sg.POPUP_YES_NO_NO: # 处理取消逻辑 - 自定义按钮文本:如果需要非英文按钮,可使用
popup_custom()自定义按钮列表:result = sg.popup_custom("是否继续?", button_list=["确认", "取消"]) if result == "确认": sg.popup("继续流程")
内容的提问来源于stack exchange,提问作者user26149746
相关产品推荐
相关产品推荐

