Tkinter画布滚动条变灰



我尝试过遵循一些教程来了解如何滚动画布,但它总是以灰色结尾。我试着在画布上添加一个滚动区域,但我不明白,只是没有变灰,但仍然什么都没做。

我的代码(运行后将其垂直调整为较短,但仍将变灰(:

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()

不应使用pack()将帧self.left放入self.canvas,而应使用self.canvas.create_window(0, 0, window=self.left, anchor='nw')

此外,您不应该将滚动条放入self.left帧,而应该将其放入self.bottom帧,并将其打包到LEFT侧。

最后,您需要更新self.canvasscrollregion以使滚动条工作。

以下是基于您的修改代码:

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()

最新更新