Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีเพิ่มความเร็วการเลื่อน (Scrolling) เมื่อแสดงข้อความมากใน Tkinter

Tkinter สามารถใช้แสดงไฟล์ข้อความและโหลดบน Canvas ได้ ไฟล์ข้อความสามารถนำไปใช้เพื่อวัตถุประสงค์อื่นๆ เช่น จัดการข้อมูล ดึงข้อมูล และแสดงข้อมูลสำหรับการใช้งานอื่นๆ

สมมติว่าเราต้องอ่านข้อความใน Tkinter Canvas ที่มีมากกว่า 10,000 บรรทัด จะใช้เวลานานในการค้นหา Query เฉพาะใน Canvas หลังโหลดไฟล์ข้อความ เพื่อจัดการไฟล์ข้อความขนาดใหญ่ เราสามารถเพิ่มความตอบสนองได้โดยเพิ่ม Y Scrollbar เราจะสร้าง Side Controller Widget โดยใช้ Scrollbar Widget

ก่อนอื่น เราจะเปิดและอ่านไฟล์โดยใช้เมธอด "open" แล้วเพิ่ม Scrollbar ในแกน Y ของ Tkinter Frame เพื่อเพิ่ม Scrollbar ใน Frame เราสามารถสร้างอินสแตนซ์ได้โดยใช้ Widget Scrollbar ซึ่งรับ Window Instance เป็นพารามิเตอร์และกำหนดคุณสมบัติอื่นๆ ของ Scrollbar (ด้านของ Scrollbar, แกน)

ตัวอย่าง

# Importing the tkinter library in the notebook
from tkinter import *

# Create an instance of the tkinter frame
win = Tk()
win.geometry("700x300")

# Create instance of Scrollbar object and define the property of the scrollbar
scrollbar = Scrollbar(win)
scrollbar.pack(side=RIGHT, fill=Y)

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

# Open and read the file using open method
file = open('file.txt', 'r').readlines()
for i in file:
    listbox.insert(END, i)

# Define the property of the widget
listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=listbox.yview)

# Display the canvas until the END button is not pressed.
mainloop()

ผลลัพธ์

การรันโค้ดข้างต้นจะเปิด Canvas พร้อม Scrollbar ด้านข้าง

วิธีเพิ่มความเร็วการเลื่อน (Scrolling) เมื่อแสดงข้อความมากใน Tkinter