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

Tkinter中Entry组件调用get方法返回.!entry的问题如何修复

问题根源

  • 执行顺序错误:按钮绑定的回调逻辑先销毁了OTP输入窗口,再尝试读取Entry组件的输入值,窗口销毁后组件已被释放,get()方法无法正常取值,只会返回组件的内部标识字符串.!entry
  • Tkinter用法不规范:不要在程序中多次实例化tk.Tk(),次级窗口请用tk.Toplevel()实现,同时原代码中的window_1.destroy缺少括号,没有实际执行销毁操作
  • 逻辑阻塞问题:原代码中window_1.mainloop()会阻塞后续代码执行,只有关闭窗口后才会执行两次密码一致性判断,不符合交互逻辑

修复后完整代码

from twilio.rest import Client
import random, tkinter as tk

def forgot_p():
    account_sid = 'ACCOUNT_SID'
    auth_token = 'AUTH_TOKEN'
    client = Client(account_sid, auth_token)
    OTP = random.randint(1,1000000)
    # 测试阶段可注释掉twilio调用,直接打印OTP调试
    message = client.messages.create(body=str(OTP), from_='+18888888888', to='+19999999999')
    print(f"调试OTP:{OTP}")

    window = tk.Tk()
    label = tk.Label(text='Please enter your OTP')
    opt_num = tk.Entry()
    # 调整执行顺序:先读取输入再销毁窗口
    def check_and_destroy():
        input_otp = opt_num.get()
        window.destroy()
        try:
            input_otp = int(input_otp)
        except:
            print("OTP格式非法")
            return
        if input_otp == OTP:
            new_password()
        else:
            print('OTP校验失败')

    button = tk.Button(text='Check OTP', command=check_and_destroy)
    label.pack()
    opt_num.pack()
    button.pack()
    window.mainloop()

def new_password():
    window_1 = tk.Toplevel()
    label_1 = tk.Label(window_1, text='Please enter your new password twice')
    text = tk.Entry(window_1, show='*')
    text_1 = tk.Entry(window_1, show='*')
    
    def check_pwd():
        p1 = text.get()
        p2 = text_1.get()
        if p1 == p2 and p1.strip():
            print('password changed')
            window_1.destroy()
        else:
            tk.Label(window_1, text='两次输入不一致,请重新输入', fg='red').pack()

    submit_btn = tk.Button(window_1, text='提交', command=check_pwd)
    label_1.pack()
    text.pack()
    text_1.pack()
    submit_btn.pack()

if __name__ == "__main__":
    forgot_p()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:45:04