如何实现点击按钮时打印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
相关产品推荐
相关产品推荐

