Tkinter获取Entry输入值返回.!entry而非用户输入的解决方法
问题原因
代码中Username、Password存储的是tkinter的Entry输入框组件对象,而非用户输入的文本内容。直接打印、写入组件对象时,tkinter会输出组件的内部路径标识,也就是你看到的.!entry、.!entry2结果。
另外原代码逻辑存在顺序错误:在addData函数中先执行win.destroy()销毁窗口,再尝试读取输入,窗口销毁后组件资源会被回收,无法正常获取值。
修复方案
- 读取输入框真实内容需要调用
Entry组件的get()方法,该方法会返回输入框内的字符串内容 - 调整执行顺序:先读取所有输入内容,再销毁窗口
- 建议区分组件变量和存储输入内容的变量,避免混淆
修复后完整代码
import tkinter from tkinter import * from tkinter import messagebox def newUser(): global win win = Tk() win.title("Prototype Register") win.geometry("500x300") win.option_add("*font", "segoeui 15 bold italic") win.resizable(False, False) global username_entry global password_entry Label(win, text="Please create a user name and password").place(x=20, y=10) win.option_add("*font", "segoeui 20 bold italic") Label(win, text="Username").place(x=30, y=50) Label(win, text="Password").place(x=30, y=110) username_entry = Entry(win) username_entry.place(x=180, y=50) password_entry = Entry(win) password_entry.place(x=180, y=110) Button(win, text="Create User", command=addData, height=2, width=10, bd=4).place(x=180, y=170) # 补充原代码缺失的主循环,窗口才能正常交互 win.mainloop() def addData(): # 先获取输入值,再销毁窗口 input_username = username_entry.get() input_password = password_entry.get() win.destroy() with open("Userdata.txt", "a", encoding="utf-8") as f: f.write(f"{input_username},{input_password}\n") newUser()
可选优化:给密码输入框添加
show="*"参数可实现输入掩码,隐藏真实输入内容;使用with上下文管理器处理文件写入可自动关闭文件,避免资源泄漏。
内容的提问来源于stack exchange,提问作者Garry The Bear
相关产品推荐
相关产品推荐

