tkinter实现一个滚动条同时控制两个部件
程序员文章站
2022-03-11 10:56:52
...
import tkinter as tk
def Wheel(event):#鼠标滚轮动作
print(str(-1*(event.delta/120)))#windows系统需要除以120
text2.yview_scroll(int(-1*(event.delta/120)), "units")
text1.yview_scroll(int(-1*(event.delta/120)), "units")
return "break"
def ScrollCommand(*xx):#在滚动条上点击、拖动等动作
print(*xx)
text1.yview(*xx)
text2.yview(*xx)
root=tk.Tk()
frame1=tk.Frame(root)
frame1.pack()
text1=tk.Text(frame1)
text1.grid(row=0,column=0)
text2=tk.Text(frame1)
text2.grid(row=0,column=2)
scrollbar1=tk.Scrollbar(frame1,orient="vertical",command=ScrollCommand)
text1.configure(yscrollcommand=scrollbar1.set)
scrollbar1.grid(row=0,column=1,sticky='ns')
for ii in range(50):
text1.insert(tk.INSERT,str(ii)+'\n')#便于展示效果
text2.insert(tk.INSERT,str(ii)+'\n')
text1.bind("<MouseWheel>", Wheel)
scrollbar1.bind("<MouseWheel>", Wheel)
text2.bind("<MouseWheel>", Wheel)
root.mainloop()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
效果如下
在text1、text2、scrollbar区域使用鼠标滚轮,均可以同步纵向滚动这三个对象;在中部滚动条上点击、拖动,也可以滚动两侧的对象
</div><div><div></div></div>
<link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-60ecaf1f42.css" rel="stylesheet">
</div>
</article>