选择Listbox选项后在Text组件中显示光标异常问题
Tkinter Listbox选中后Text组件光标不显示问题
在Tkinter代码中,Listbox与Text组件配合时存在异常:选中Listbox的选项后,代码尝试将光标定位到Text组件的指定位置并获取焦点,但光标并未显示;只有按下Tab键手动激活Text组件后,光标才会正常出现。
对应的Listbox实现代码如下:
import tkinter as tk list_cursor_pos = ['2.5', '5.10', '8.15'] def on_listbox_select(event): i = listbox.curselection()[0] cursor_pos = list_cursor_pos[i] text_box.focus_set() text_box.mark_set("insert", cursor_pos) text_box.see(cursor_pos) text_box.event_generate('<FocusIn>') root = tk.Tk() # Listbox listbox = tk.Listbox(root) listbox.pack(side = tk.LEFT, padx=10, pady=10) for e in list_cursor_pos: listbox.insert('end', f'Go to {e} in the text') listbox.bind("<<ListboxSelect>>", on_listbox_select) # Text box text_box = tk.Text(root, height=15, width=50) text_box.pack(side = tk.RIGHT, padx=10, pady=10) # Create content for text box content = "" for i in range(9): content += f"{i+1}:234567890123456789\n" text_box.insert("1.0", content) root.mainloop()
而改用Button组件实现相同的光标定位功能时,光标能够正常显示在Text组件中:
import tkinter as tk def set_cursor_pos(): cursor_pos = "2.5" text_box.focus_set() text_box.mark_set("insert", cursor_pos) root = tk.Tk() myButton = tk.Button(root, text = "Set cursor position at 2.5", command=set_cursor_pos) myButton.pack(side = tk.LEFT, padx=10, pady=10) myButton.focus_set() # Text box text_box = tk.Text(root, height=15, width=50) text_box.pack(side = tk.RIGHT, padx=10, pady=10) content = "" for i in range(9): content += f"{i+1}:234567890123456789\n" text_box.insert("1.0", content) root.mainloop()
内容的提问来源于stack exchange,提问作者Daniel Louw
相关产品推荐
相关产品推荐

