我尝试按照一些教程进行操作,以了解如何使画布滚动,但是最终总是变灰。我曾尝试在画布上添加一个滚动区域,但我不了解它,只是了解到它没有变灰,却什么也没做。
我的代码(运行后将其调整为垂直方向较短,并且仍会变灰):
self.main_window = Tk()
self.root = Frame(self.main_window, bg="white")
self.root.pack(fill=BOTH, expand=1)
# TOP SECTION
self.top = Frame(self.root, bg="white")
self.top.pack(fill=BOTH, expand=1)
Label(self.top, text="#########################################").pack()
# BOTTOM SECTION
self.bottom = Frame(self.root, bg="white")
self.bottom.pack(fill=BOTH, expand=1)
# BOTTOM-LEFT SECTION
self.canvas = Canvas(self.bottom, bg="white")
self.canvas.pack(fill=BOTH, expand=1, side=LEFT)
self.left = Frame(self.canvas)
self.left.pack(fill=BOTH, expand=1)
left_scroll = Scrollbar(self.left, orient=VERTICAL)
left_scroll.pack(side=RIGHT, fill=Y)
left_scroll.config(command=self.canvas.yview)
self.canvas.configure(yscrollcommand=left_scroll.set)
for root, dirs, files in os.walk("C:\\", topdown=True):
full = dirs + files
for i in full:
Button(self.left, text=i, bg="white", anchor="w", relief=SOLID, borderwidth=0).pack(fill=BOTH)
break
# BOTTOM-RIGHT SECTION
self.right = Frame(self.bottom, bg="white")
self.right.pack(fill=BOTH, expand=1, side=RIGHT)
Label(self.right, text="##########################").pack()
Label(self.right, text="##########################").pack()
self.main_window.mainloop()
答案 0 :(得分:4)
您不应使用pack()
将框架self.left
放入self.canvas
,而应使用self.canvas.create_window(0, 0, window=self.left, anchor='nw')
。
此外,您不应将滚动条放入框架self.left
中,而应将滚动条放入框架self.bottom
中,并将其包装在侧面LEFT
中。
最后,您需要更新scrollregion
中的self.canvas
才能使滚动条起作用。
下面是根据您的代码修改的代码:
self.main_window = Tk()
self.root = Frame(self.main_window, bg="white")
self.root.pack(fill=BOTH, expand=1)
# TOP SECTION
self.top = Frame(self.root, bg="white")
self.top.pack(fill=BOTH, expand=1)
Label(self.top, text="#########################################").pack()
# BOTTOM SECTION
self.bottom = Frame(self.root, bg="white")
self.bottom.pack(fill=BOTH, expand=1)
# BOTTOM-LEFT SECTION
self.canvas = Canvas(self.bottom, bg="white")
self.canvas.pack(fill=BOTH, expand=1, side=LEFT)
self.left = Frame(self.canvas)
#self.left.pack(fill=BOTH, expand=1)
self.canvas.create_window(0, 0, window=self.left, anchor='nw') ###
left_scroll = Scrollbar(self.bottom, orient=VERTICAL) ### self.left to self.bottom
left_scroll.pack(side=LEFT, fill=Y) ### side=RIGHT to side=LEFT
left_scroll.config(command=self.canvas.yview)
self.canvas.configure(yscrollcommand=left_scroll.set)
for root, dirs, files in os.walk("C:\\", topdown=True):
full = dirs + files
for i in full:
Button(self.left, text=i, bg="white", anchor="w", relief=SOLID, borderwidth=0).pack(fill=BOTH)
break
### update scrollregion of self.canvas
self.left.update()
self.canvas.configure(scrollregion=self.canvas.bbox('all'))
# BOTTOM-RIGHT SECTION
self.right = Frame(self.bottom, bg="white")
self.right.pack(fill=BOTH, expand=1, side=RIGHT)
Label(self.right, text="##########################").pack()
Label(self.right, text="##########################").pack()
self.main_window.mainloop()