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

问题描述

有什么方法可以检测 tkinter 中 Entry 小部件中的选择,就像我们在 Text 小部件 txt.get(SEL_FirsT,SEL_LAST) 和 txt.tag_ranges("sel") 中一样

解决方法

如果您只想检查选择是否存在,您可以使用 Entry.select_present() 方法,如果选择存在,则返回 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()