You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现tkinter simpledialog.askstring点击取消时终止后续代码执行

问题根因

simpledialog.askstring() 的返回规则如下:

  • 用户输入内容后点击「确定」:返回输入的字符串内容
  • 用户点击「取消」/直接关闭输入弹窗:返回None

现有代码没有对取消场景的返回值做拦截判断,因此无论用户在输入弹窗点击取消还是确定,都会继续执行后续的askokcancel弹窗逻辑,不符合预期。

修复方案

拿到askstring的返回值后,第一时间判断如果值为None,直接return终止当前函数流程即可,后续代码不会再执行。

修复后的完整代码:

from tkinter import *
from tkinter import messagebox, simpledialog
from tkinter.messagebox import askokcancel, showinfo, WARNING

app = []


def main():
    USER_INP = simpledialog.askstring(title="App Name",
                                      prompt="Insert the name of the app:")
    # 拦截取消操作,直接终止流程
    if USER_INP is None:
        return

    print(USER_INP)
    answer = askokcancel(
        title='DELETION',
        message='Are you sure?',
        icon=WARNING)

    if answer:
        print(answer)
        messagebox.showinfo("INFO", "User pressed yes")
        app.append(USER_INP)
    else:
        messagebox.showinfo("INFO", "User pressed cancel")


root = Tk()

myButton = Button(root, text='input', command=main)
myButton.pack()

root.mainloop()
可选优化

如果需要同时拦截「用户没输入任何内容直接点确定」的场景,可以把判断条件改成if not USER_INP:,这样点取消、输入空字符串/全空白内容点确定的场景都会直接终止流程。

内容的提问来源于stack exchange,提问作者AfterHover

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 06:24:25