B
The wiring of the text field to the scrubbar requires that the scrulbar manage the textual field (in your case, the required piece of the file is downloaded) and the text field was managed by a scrubbard the entry of the beginning and end of the shell through the method. set♪ In the normal connection, this method is transmitted to the text field through the parameter yscrolle.g. text = Text(..., yscroll=vscroll.set) or text['yscroll'] = vscroll.set (depending on which object was formerly created - text field or scrubbar) and the object of the text field causes this method when necessary. In your case, this method must be forced to update the state of the shelf.Other comments:move Two parameters must be accepted (this can be seen by mistakes that put the interpreter in the console) for the position is the second parameter, and it should be inserted in the position. float a intand this position is a poultry position from 0.0 to 1.0 (from 0 per cent to 100 per cent) rather than a change of position.The position to be transferred in the file is defined as the position of the polka (from 0.0 to 1.0) multiplied by the size of the file, no complex logic is needed.f.read(...) Loads the number of symbols, but it is more logical to download the required number of lines through [file.readline() for _ in range(text_height)]Size flat - 10 per cent of the total strip (0.1 in line) scrolly.set(0.0, 0.1) and scrolly.set(position, position + 0.1)) You can make a size fit, which part of the file is loaded, but I was lazy and it works. But in principle there's nothing to do with it.The rest of you look in the code comments.from tkinter import *
import tkinter.filedialog as fd
import os
text_height = 40
file = None
file_size = None
def open_file():
global file, file_size
file_name = fd.askopenfilename()
file_size = os.path.getsize(file_name)
if file:
file.close()
file = open(file_name, 'r')
text_lines = [file.readline() for _ in range(text_height)]
text.delete(1.0, END)
text.insert(END, ''.join(text_lines))
# Метод set устанавливает позицию начала и конца ползунка
# Первоначальная позиция ползунка - в самом верху,
# конец ползунка - на 10% (от общей высоты скролбара) ниже
scrolly.set(0.0, 0.1)
def move(command, position=0):
# command - обычно строка "moveto", position - значение от "0.0" до "1.0"
# Файл открыт?
if file is None:
return
position = float(position)
# Не давать прокрутить выше или ниже границ файла
# (если продолжать тянуть вниз или вверх после того как ползунок уперся в край,
# в функцию будут приходить значения position меньше 0 или больше 1)
if position < 0.0:
position = 0.0
if position > 1.0:
position = 1.0
file.seek(file_size*position)
if position > 0.0:
# Если не начало файла, то считать что попали на середину строки, пропускаем ее
try:
file.readline()
except UnicodeDecodeError:
# Кидает это исключение, если переход на середину utf-8 символа
# Чтобы корректно обрабатывать такие ситуации, нужно файл открывать в бинарном режиме,
# и в процессе чтения текст декодировать
pass
text_lines = [file.readline() for _ in range(text_height)]
text.delete(1.0, END)
text.insert(END, ''.join(text_lines))
scrolly.set(position, position + 0.1) # Обновить позицию "ползунка"
window = Tk()
btn_open = Button(window, text="Открыть файл", command=open_file)
btn_open.grid(column=3, row=0)
text = Text(window, width=200, height=text_height+1)
text.grid(column=1, row=1)
scrolly = Scrollbar(command=move)
scrolly.grid(column=2, row=1, sticky=NS)
scrolly.set(0.0, 1.0) # Устанавливаем первоначальную высоту "ползунка" полосы прокрутки на 100%
window.mainloop()