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

如何实现点击按钮时打印Tkinter输入框的内容?

解决点击按钮打印输入框内容的问题

你的代码核心问题:点击"CONFIRMER"按钮时,mdpcheck函数会重新调用mdp(),生成全新的弹窗和输入框,你获取的是这个新输入框的空值,而非用户实际输入的那个输入框内容。

下面提供两种可行的解决方式:

方式一:使用闭包(推荐)

将mdpcheck定义在mdp函数内部,让它直接访问已创建的输入框对象,无需重新生成弹窗:

def mdp():
    new3 = Toplevel(win)
    window_height = 160
    window_width = 300
    screen_width = new3.winfo_screenwidth()
    screen_height = new3.winfo_screenheight()
    x_cordinate = int((screen_width / 2) - (window_width / 2))
    y_cordinate = int((screen_height / 2) - (window_height / 2))
    new3.geometry("{}x{}+{}+{}".format(window_width, window_height, x_cordinate, y_cordinate))
    text1 = ttk.Label(new3, text="MOT DE PASSE:")
    text1.place(x=50, y=30)
    entry1 = Entry(new3, show="*")
    entry1.place(x=50, y=50, width=200, height=20)
    
    # 内部函数直接访问外部的entry1
    def mdpcheck():
        réponse2 = entry1.get()
        print(réponse2)
    
    b1 = Button(new3, text="CONFIRMER", command=mdpcheck)
    b1.place(x=100, y=80, width=100, height=20)

方式二:使用全局变量

通过全局变量让mdpcheck访问到已创建的输入框,这种方式简单但不推荐(全局变量易引发代码维护问题):

# 定义全局变量存储输入框对象
entry1 = None

def mdp():
    global entry1
    new3 = Toplevel(win)
    window_height = 160
    window_width = 300
    screen_width = new3.winfo_screenwidth()
    screen_height = new3.winfo_screenheight()
    x_cordinate = int((screen_width / 2) - (window_width / 2))
    y_cordinate = int((screen_height / 2) - (window_height / 2))
    new3.geometry("{}x{}+{}+{}".format(window_width, window_height, x_cordinate, y_cordinate))
    text1 = ttk.Label(new3, text="MOT DE PASSE:")
    text1.place(x=50, y=30)
    entry1 = Entry(new3, show="*")
    entry1.place(x=50, y=50, width=200, height=20)
    b1 = Button(new3, text="CONFIRMER", command=mdpcheck)
    b1.place(x=100, y=80, width=100, height=20)


def mdpcheck():
    global entry1
    réponse2 = entry1.get()
    print(réponse2)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 06:15:22