Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách tăng tốc độ cuộn (scrolling) khi hiển thị nhiều text trong Tkinter?

Tkinter có thể render file text lên canvas. Với file lớn (>10.000 dòng), tìm kiếm chậm. Giải pháp: thêm thanh cuộn dọc (Y Scrollbar) dùng Scrollbar Widget.

Mở file bằng open(), đọc dòng, thêm vào Listbox, gán scrollbar.

Ví dụ

# Import tkinter
from tkinter import *

win = Tk()
win.geometry("700x300")

# Tạo Scrollbar
scrollbar = Scrollbar(win)
scrollbar.pack(side=RIGHT, fill=Y)

listbox = Listbox(win, height=300, width=100)
listbox.pack()

# Đọc file
file = open('file.txt', 'r').readlines()
for i in file:
    listbox.insert(END, i)

# Kết nối scrollbar với listbox
listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=listbox.yview)

mainloop()

Kết quả

Chạy code mở canvas có scrollbar bên cạnh.

Cách tăng tốc độ cuộn (scrolling) khi hiển thị nhiều text trong Tkinter?