tkinter Entry 小部件检测是否有任何选择

tkinter Entry widget detect if there is any selection

有什么方法可以检测 tkinter 中的条目小部件中的选择,就像我们在文本小部件中得到的那样 txt.get(SEL_FIRST, SEL_LAST) 和 txt.tag_ranges("选择")

如果您只想检查是否存在选择,您可以使用 Entry.select_present() 方法,如果存在选择,则 returns True

如果你想得到选择你可以使用Entry.selection_get()

最小示例:

from tkinter import *

def selection_present():
    print(entry.select_present())
    if entry.select_present():
        print(entry.selection_get())

root = Tk()

entry = Entry(root)
entry.pack()

Button(root, text="Check selection", command=selection_present).pack()

root.mainloop()