如何使滚动条随光标移动

时间:2019-04-29 20:28:17

标签: python-3.x tkinter

我想将光标与滚动条绑定,因此当我跳至下一个“文本”小部件时,窗口将滚动到光标所在的位置。

在我的代码中,我有许多“文本”小部件,并且该窗口是可滚动的。我使用ctrl-tab移至下一个“文本”小部件,但是当光标位于不在窗口中的小部件中时,滚动条不会移动。我知道滚动条已绑定到鼠标滚轮。我还如何使滚动条与光标一起移动。

import tkinter as tk
from tkinter import *
from tkinter import ttk


def on_mousewheel(event):
    canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")

def on_configure(event):
    # update scrollregion after starting 'mainloop'
    # when all widgets are in canvas
    canvas.configure(scrollregion=canvas.bbox('all'))
    canvas.itemconfigure('internal_frame', width=event.width - 10)

# Create new window
new_win = tk.Tk()
new_win.focus_force()

# Create a canvas with a scrollbar
canvas = tk.Canvas(new_win)
canvas.grid(row=0, column=0, sticky=tk.N + tk.S + tk.E + tk.W)

scrollbar = ttk.Scrollbar(new_win, command=canvas.yview)
scrollbar.grid(sticky=(N, S), row=0, column=1)
canvas.config(yscrollcommand=scrollbar.set)

# --- put frame in canvas ---
new_frame = tk.Frame(canvas)
new_frame.grid(row=0, column=0, sticky=tk.N + tk.S + tk.E + tk.W)

canvas.create_window((0, 0), window=new_frame, anchor='nw', tags=('internal_frame',))

# update scrollregion after starting 'mainloop when all widgets are in canvas
canvas.bind('<Configure>', on_configure)
new_win.bind('<MouseWheel>', on_mousewheel)

# Add Widgets
insert_box = []
for i in range(10):
    insert_box.append(tk.Text(new_frame, borderwidth=2, height=4, width=30, wrap=WORD))
    insert_box[i].grid(column=1, row=i, sticky=tk.N + tk.S + tk.E + tk.W)

# configure
new_win.grid_columnconfigure(0, weight=1)
new_win.grid_rowconfigure(0, weight=1)

new_frame.grid_columnconfigure(1, weight=1)
new_frame.grid_rowconfigure(0, weight=1)

canvas.grid_columnconfigure(0, weight=1)
canvas.grid_rowconfigure(0, weight=1)

new_win.mainloop()

1 个答案:

答案 0 :(得分:0)

如果您想通过Ctrl + Tab或光标移至当前的Text小部件,因为您已经有insert_box的列表。只需将yview_moveto命令绑定到您创建到Text的每个FocusIn小部件:

for i in insert_box:
    i.bind("<FocusIn>",lambda e, i=i:canvas.yview_moveto(insert_box.index(i)/len(insert_box)))
相关问题