Customtkinter中root.focus_get()无法检测CTkEntry焦点问题
问题解决:CTkEntry绑定回车无输出的问题
问题原因
customtkinter的CTkEntry是封装了原生tkinter Entry的自定义组件,当它获得焦点时,root.focus_get()返回的是其内部的原生Entry对象,而非你定义的custom_entry实例。直接用==判断两个对象是否相等会不成立,因此无法触发"custom_entry"的打印逻辑。
解决方案1:通过内部组件属性判断
利用CTkEntry的_entry属性(存储了内部原生Entry组件)进行焦点匹配:
import customtkinter from tkinter import * def test(event): # 判断焦点是否在CTkEntry的内部原生组件上 if root.focus_get() == custom_entry._entry: print("custom_entry") elif root.focus_get() == ttk_entry: print("ttk_entry") root = customtkinter.CTk() custom_entry = customtkinter.CTkEntry(root) custom_entry.pack() ttk_entry = Entry(root) ttk_entry.pack() root.bind("<Return>", test) root.mainloop()
解决方案2:给组件单独绑定事件
避免全局绑定后的焦点判断,直接为每个输入框单独绑定<Return>事件,逻辑更清晰:
import customtkinter from tkinter import * def on_custom_entry_return(event): print("custom_entry") def on_ttk_entry_return(event): print("ttk_entry") root = customtkinter.CTk() custom_entry = customtkinter.CTkEntry(root) custom_entry.pack() custom_entry.bind("<Return>", on_custom_entry_return) ttk_entry = Entry(root) ttk_entry.pack() ttk_entry.bind("<Return>", on_ttk_entry_return) root.mainloop()
内容的提问来源于stack exchange,提问作者black forest
相关产品推荐
相关产品推荐

