如何使用Custom Tkinter实现密码的显示/隐藏功能?
使用CustomTkinter实现密码显示/隐藏功能
你的代码思路没问题,只需小调整就能正常运行。CustomTkinter的CTkEntry组件和标准Tkinter的Entry用法逻辑一致,核心是通过切换show参数控制密码可见性。
修正后的完整代码
import customtkinter def toggle_password(): # 切换密码显示状态 if txt.cget('show') == '*': txt.configure(show='') toggle_btn.configure(text='隐藏密码') else: txt.configure(show='*') toggle_btn.configure(text='显示密码') # 初始化CustomTkinter应用环境 customtkinter.set_appearance_mode("light") customtkinter.set_default_color_theme("blue") root = customtkinter.CTk() root.geometry("300x150") root.title("密码显示切换") # 创建默认隐藏的密码输入框 txt = customtkinter.CTkEntry(root, show='*', width=200, placeholder_text="请输入密码") txt.pack(pady=20) # 创建状态切换按钮 toggle_btn = customtkinter.CTkButton(root, text='显示密码', command=toggle_password) toggle_btn.pack() root.mainloop()
关键细节说明
- 初始化
CTkEntry时设置show='*',让输入内容默认以星号隐藏 - 通过
cget('show')获取当前显示状态,用configure()修改show参数实现切换 - 同步更新按钮文本,让用户清晰知道当前操作对应的状态
- 建议使用CustomTkinter自带的
CTk()作为主窗口,能更好适配组件样式
内容的提问来源于stack exchange,提问作者Boris Sharikov
相关产品推荐
相关产品推荐

