我正在尝试制作一个具有设定高度的框架,并带有垂直滚动条来响应鼠标滚动事件。框架需要包含框架,因此没有可以使用的内置Tk小部件。这是我正在使用的Python 3代码,源于此处的几个相关答案:
import tkinter as tk
class VertScrollingFrame(tk.Frame):
def __init__(self, root):
super().__init__(root)
self.canvas = tk.Canvas(root)
self.frame = tk.Frame(self.canvas)
self.bar = tk.Scrollbar(root, orient = "vertical", command = self.canvas.yview)
self.bar.lift(self.frame)
self.canvas.configure(yscrollcommand = self.bar.set)
self.bar.pack(side = "right", fill = "y")
self.canvas.pack(side = "left", fill = 'both', expand = True)
self.canvas.create_window(
(4, 4),
window = self.frame,
anchor = "nw",
tags = "self.frame",
)
#self.frame.pack()
def on_cfg(_):
self.canvas.configure(scrollregion = self.canvas.bbox("all"))
self.frame.bind('<Configure>', on_cfg)
def on_scroll(event):
if event.delta:
amount = round(-event.delta / 120)
else:
amount = {4: -1, 5: 1}[event.num] * 2
self.canvas.yview_scroll(amount, "units")
bind_keys = {'<MouseWheel>', '<Button-4>', '<Button-5>'}
def scroll_bind(_):
for key in bind_keys:
self.canvas.bind_all(key, on_scroll)
def scroll_unbind(_):
for key in bind_keys:
self.canvas.unbind_all(key)
self.frame.bind('<Enter>', scroll_bind)
self.frame.bind('<Leave>', scroll_unbind)
root = tk.Tk()
win = tk.Toplevel(root)
sf = VertScrollingFrame(win)
for _ in range(20):
f = tk.Frame(sf.frame)
for x in range(12):
tk.Button(f, text = str(x)).pack(side = 'left')
f.pack()
sf.pack()
root.mainloop()
我在滚动框架中填充了宽阔的按钮网格,并且画布似乎在水平调整大小以适合它们,但是ScrollingFrame
不是。它只是切断了内容的右侧。如何使框架展开以使其内容水平放置?
在未注释self.frame.pack()
的情况下,我得到了另一个不同的错误结果:奇怪的是,垂直和水平方向都裁剪了按钮网格,并且没有滚动的内容。