Tkinter两个Text组件共用滚动条时鼠标滚轮无响应如何解决
问题排查与修复
你代码中存在4个核心问题导致滚轮失效、联动异常:
- 鼠标滚轮回调函数写法错误:
my_text.yview_scroll.int是无效写法,yview_scroll本身是可调用方法,不需要加.int后缀 - 存在重复定义的
_bound_to_mousewheel函数,全局函数和类方法冲突,你如果是用类封装代码就保留带self的类方法,用全局写法就保留无self的全局版本即可 - 滚动条的
command参数绑定的scroll方法未定义,需要自己实现联动行号组件和编辑区组件的滚动逻辑 - 鼠标滚轮触发滚动时只处理了编辑区,没有同步更新行号组件的滚动位置
以下是修复后的完整可运行代码(全局写法版本,类写法只需把变量和方法加self前缀即可):
from tkinter import * root = Tk() root.title("带行号记事本") # 自定义滚动联动方法,同时控制两个Text组件滚动 def scroll(*args): my_text.yview(*args) lines.yview(*args) def _on_mousewheel(event): # 修正滚动调用写法,同时滚动编辑区和行号 scroll_amount = int(-1*(event.delta/120)) my_text.yview_scroll(scroll_amount, "units") lines.yview_scroll(scroll_amount, "units") def _bound_to_mousewheel(event): root.bind_all("<MouseWheel>", _on_mousewheel) # 新增离开解绑方法,避免离开编辑区后滚轮还触发记事本滚动 def _unbound_to_mousewheel(event): root.unbind_all("<MouseWheel>") my_frame = Frame(root, background="#2A2F31") my_frame.pack(pady=5, fill=BOTH, expand=True) my_frame.bind('<Enter>', _bound_to_mousewheel) my_frame.bind('<Leave>', _unbound_to_mousewheel) text_scroll = Scrollbar(my_frame) text_scroll.pack(side=RIGHT, fill=Y) text_scroll2 = Scrollbar(my_frame, orient='horizontal') text_scroll2.pack(side=BOTTOM, fill=X) lines = Text(my_frame, width= 5, borderwidth = '0', font=("Helvetica", 16), yscrollcommand=text_scroll.set, fg="WHITE", bg="#2f3136", wrap='none', undo=True) lines.pack(side=LEFT, fill=Y) lines.config(state='disabled') my_text = Text(my_frame, font=("Helvetica", 16), selectbackground="Light Blue", selectforeground="Black", undo=True, yscrollcommand=text_scroll.set, bg="#2f3136", fg="WHITE", wrap='none', xscrollcommand=text_scroll2.set, borderwidth = '0') my_text.pack(fill=BOTH, expand=True) text_scroll.config(command=scroll) # 绑定到自定义的联动滚动方法 text_scroll2.config(command=my_text.xview) # 可选功能:监听编辑区内容变化自动更新行号 def update_line_numbers(event=None): lines.config(state=NORMAL) lines.delete(1.0, END) line_count = str(my_text.get(1.0, END)).count("\n") for i in range(1, line_count + 1): lines.insert(END, f"{i}\n") lines.config(state=DISABLED) lines.yview_moveto(my_text.yview()[0]) my_text.bind("<KeyRelease>", update_line_numbers) my_text.bind("<Configure>", update_line_numbers) update_line_numbers() root.mainloop()
内容的提问来源于stack exchange,提问作者No-Question123
相关产品推荐
相关产品推荐

