Tkinter 教程-滾動條
Jinku Hu
2023年1月30日
Tkinter
Tkinter Scrollbar
Tkinter 滾動條控制元件通常用於滾動控制元件,比如 ListBox,Text 或 Canvas 在豎直方向上滾動或 Entry 在水平方向滾動。它在合適的位置顯示滑塊。
Tkinter 滾動條
import tkinter as tk
class Scrollbar_Example:
def __init__(self):
self.window = tk.Tk()
self.scrollbar = tk.Scrollbar(self.window)
self.scrollbar.pack(side="right", fill="y")
self.listbox = tk.Listbox(self.window, yscrollcommand=self.scrollbar.set)
for i in range(100):
self.listbox.insert("end", str(i))
self.listbox.pack(side="left", fill="both")
self.scrollbar.config(command=self.listbox.yview)
self.window.mainloop()
if __name__ == "__main__":
app = Scrollbar_Example()

self.scrollbar = tk.Scrollbar(self.window)
它啟動 Scrollbar 例項。
self.listbox = tk.Listbox(self.window, yscrollcommand=self.scrollbar.set)
self.scrollbar.config(command=self.listbox.yview)
我們需要同時配置 Listbox 和 Scrollbar 以使他們能正確地耦合在一起。
- 將
yscrollcommand回撥設定為Scrollbar的set。yscrollcommand是由滾動條控制的可滾動控制元件的選項,用於與垂直滾動條進行通訊。 - 設定
Scrollbar的command到Listbox的yview。當使用者移動Scrollbar的滑塊時,它將使用適當的引數呼叫yview方法。
Tkinter 水平滾動條
水平滾動條用於在水平方向滾動視窗控制元件 Text 和 Entry 等。
import tkinter as tk
class Scrollbar_Example:
def __init__(self):
self.window = tk.Tk()
self.scrollbar = tk.Scrollbar(self.window, orient=tk.HORIZONTAL)
self.scrollbar.pack(side="bottom", fill="x")
self.text = tk.Text(self.window, wrap="none", xscrollcommand=self.scrollbar.set)
self.text.insert("end", str(dir(tk.Scrollbar)))
self.text.pack(side="top", fill="x")
self.scrollbar.config(command=self.text.xview)
self.window.mainloop()
if __name__ == "__main__":
app = Scrollbar_Example()

self.scrollbar = tk.Scrollbar(self.window, orient=tk.HORIZONTAL)
通過將 orient 指定為 HORIZONTAL 來啟動水平滾動條。
self.text = tk.Text(self.window, wrap="none", xscrollcommand=self.scrollbar.set)
要水平滾動文字,我們需要將 xscrollcommand 設定為 Scrollbar 的 set 方法,而不是設定上面的示例中的 yscrollcommand。
self.scrollbar.config(command=self.text.xview)
相應地,水平滾動條的回撥應與 xview 方法連線,而不是與 yview 方法連線。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
