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

如何实现Tkinter Entry组件中文本的自动选中/高亮?

解决Tkinter Entry默认文本自动高亮的问题

要实现Entry组件默认文本自动高亮,让用户输入直接替换内容,你可以通过绑定焦点进入事件,在输入框获得焦点时自动选中所有文本。以下是修改后的代码:

from tkinter import *

root = Tk()

def myClick():
    hello = "Hello " + my_entry.get()
    my_label.configure(text=hello)

def on_entry_focus_in(event):
    # 选中Entry内所有文本
    event.widget.select_range(0, END)
    # 取消后续默认选中行为(避免冲突)
    return "break"

my_entry = Entry(root)
my_entry.insert(END, "Enter your name here.")
# 绑定焦点进入事件
my_entry.bind("<FocusIn>", on_entry_focus_in)
my_entry.pack()

my_button = Button(root, text="Click Me!", command=myClick)
my_button.pack()

my_label = Label(root, text="")
my_label.pack()

# 程序启动时自动让输入框获得焦点并选中文本(可选)
my_entry.focus_set()
my_entry.select_range(0, END)

root.mainloop()

关键说明:

  • select_range(0, END):选中从索引0到末尾的所有文本,实现和鼠标拖拽选中一致的高亮效果。
  • <FocusIn>事件绑定:当用户点击输入框或通过Tab切换焦点时,自动触发选中文本的操作。
  • 返回"break":阻止Tkinter默认的焦点处理行为,避免选中状态被系统默认操作覆盖。
  • 手动调用focus_set()和select_range():让程序启动时输入框就自动获得焦点并高亮文本,进一步优化用户体验。

这样用户无论是启动程序后直接输入,还是点击输入框,都能直接替换默认文本,无需手动选中删除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 19:12:04