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

Customtkinter中CTkEntry设为readonly状态时如何显示placeholder_text

解决CTkEntry只读状态下显示占位文本的问题

CTkEntry默认在设置state='readonly'时会隐藏占位文本,这是因为其底层依赖的tkinter Entry组件在只读状态下不支持原生占位文本显示。以下提供两种可行的解决方法:

方法一:自定义CTkEntry子类(推荐,支持状态切换)

通过继承CTkEntry并绑定状态变化事件,自动处理只读状态下的占位文本显示逻辑:

import customtkinter as ctk

class ReadOnlyCTkEntry(ctk.CTkEntry):
    def __init__(self, master=None, placeholder_text="", **kwargs):
        super().__init__(master, placeholder_text=placeholder_text, **kwargs)
        self.original_placeholder = placeholder_text
        self.bind("<<State>>", self.on_state_change)
        
    def on_state_change(self, event):
        current_state = self.cget("state")
        if current_state == "readonly":
            self.delete(0, ctk.END)
            self.insert(0, self.original_placeholder)
            self.configure(text_color=self._placeholder_text_color)
        else:
            if self.get() == self.original_placeholder:
                self.delete(0, ctk.END)
            self.configure(text_color=self._text_color)

# 使用示例
if __name__ == "__main__":
    gui = ctk.CTk()
    gui.geometry("200x200") 
    entrada = ReadOnlyCTkEntry(gui, placeholder_text='Hello World', state='readonly')
    entrada.pack(pady=50)
    
    # 测试状态切换功能
    def toggle_state():
        entrada.configure(state="normal" if entrada.cget("state") == "readonly" else "readonly")
    
    btn = ctk.CTkButton(gui, text="切换状态", command=toggle_state)
    btn.pack(pady=10)
    
    gui.mainloop()

方法二:手动设置(适合固定只读场景)

直接插入占位文本并调整文本颜色,再设置为只读状态:

import customtkinter as ctk

gui = ctk.CTk()
gui.geometry("200x200") 

entrada = ctk.CTkEntry(gui, placeholder_text='Hello World', state='normal')
# 插入占位文本并匹配占位文本颜色
entrada.insert(0, 'Hello World')
entrada.configure(text_color=entrada._placeholder_text_color, state='readonly')
entrada.pack(pady=50)

gui.mainloop()

注意事项

  • 方法一中的子类会自动处理状态切换时的占位文本显示/隐藏,无需额外代码维护;
  • 方法二仅适用于固定为只读状态的场景,若需要切换状态,需手动处理文本内容和颜色。

内容的提问来源于stack exchange,提问作者Kumar López

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 01:34:55