我正在使用画布中包含的小部件。我使用包几何管理器,因为它非常灵活,并且自动适应窗口小部件的大小(每行的小部件的大小和数量不是恒定的)。但有时候我有太多的小工具,他们都没有进入窗口。 所以我试图使用滚动条。
但是如果我保留pack方法,滚动条就没用了。例如,这是我的代码:
import tkinter as tk
class Interface:
def __init__(self, root):
self.root = root
self.root.bind('<Control-w>', lambda e: root.destroy())
self.canvas = tk.Canvas(self.root)
self.scrollbar = tk.Scrollbar(self.root, command=self.canvas.yview)
self.scrollbar.pack(side=tk.RIGHT, fill='y')
self.canvas.pack(side="left", fill='both', expand=True)
self.fill()
bbox = self.canvas.bbox('all')
self.canvas.configure(scrollregion=bbox, yscrollcommand=self.scrollbar.set)
self.canvas.bind("<Configure>", self.OnFrameConfigure)
def OnFrameConfigure(self, event):
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
def fill(self):
ordered_list = [['element in row {}, column {}.'.format(i, j) for j in range(i % 10 + 1)] for i in range(100)]
for elements in ordered_list:
frame = tk.Frame(self.canvas)
for e in elements:
label = tk.Label(frame, text=e)
label.pack(side=tk.LEFT)
self.label = frame
frame.pack(side=tk.TOP, pady=10)
if __name__ == '__main__':
root = tk.Tk()
Interface(root, main, machines)
root.mainloop()
当我将我的小部件封装在一个框架中并在画布中绘制此框架时,滚动条起作用。但是我松开窗口的自动尺寸对应于我的小部件的大小,当我延伸窗口时,框架粘在角落里,而不是像包装方法那样在中间。
import tkinter as tk
class Interface:
def __init__(self, root):
self.root = root
self.root.bind('<Control-w>', lambda e: root.destroy())
self.canvas = tk.Canvas(self.root)
self.scrollbar = tk.Scrollbar(self.root, command=self.canvas.yview)
+ self.frame = tk.Frame(self.canvas)
self.scrollbar.pack(side=tk.RIGHT, fill='y')
self.canvas.pack(side="left", fill='both', expand=True)
self.fill()
+ self.canvas.create_window((0, 0), window=self.frame)
bbox = self.canvas.bbox('all')
self.canvas.configure(scrollregion=bbox, yscrollcommand=self.scrollbar.set)
self.frame.bind("<Configure>", self.OnFrameConfigure)
def OnFrameConfigure(self, event):
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
def fill(self):
ordered_list = [['element in row {}, column {}.'.format(i, j) for j in range(i % 10 + 1)] for i in range(100)]
for elements in ordered_list:
+ frame = tk.Frame(self.frame)
for e in elements:
label = tk.Label(frame, text=e)
label.pack(side=tk.LEFT)
self.label = frame
frame.pack(side=tk.TOP, pady=10)
if __name__ == '__main__':
root = tk.Tk()
Interface(root, main, machines)
root.mainloop()
那么,有没有办法将pack方法保存在带有滚动条的画布中,或者是否具有在画布中绘制框架的灵活性(窗口的自动大小,小部件保持在中心)?