在 Tkinter 中顯示大量文字時如何加快滾動響應速度?


Tkinter 也可以用來渲染文字檔案並在畫布上載入它。此外,文字檔案可以用於其他目的,例如操作資料、獲取資料以及為其他用途渲染資料。

假設我們必須在包含超過 10,000 行查詢的 Tkinter 畫布檔案中讀取文字。載入文字檔案後,在畫布中搜索特定查詢將需要很長時間。為了處理如此大的文字檔案,我們可以透過新增 Y 捲軸來加快檔案的響應速度。我們將使用**捲軸部件**建立側控制器部件。

首先,我們將使用“open”方法開啟並讀取檔案,然後,我們將向 Tkinter 框架的 Y 軸新增捲軸。要在框架中新增捲軸,我們可以使用**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()

輸出

執行上述程式碼片段將開啟帶有側邊捲軸的畫布。

更新於:2021年3月6日

670 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告