Python Tkinter可滚动框架类?

时间:2015-05-03 19:05:02

标签: python tkinter scrollbar tkinter-canvas

我想根据the answer here制作一个Tkinter classFrame会自动显示/隐藏内容Scrollbar必要时。

我上面提到的答案完全符合我的需要,但需要注意的是,因为它不包含在class中,所以它不可重复使用。我认为这将非常快速和简单,但由于某些原因,我的AutoScrollbar一旦我将代码重构为自己的class,我就永远不会出现,无论{的内容有多少或几乎没有。 {1}}被窗口大小调整隐藏。

Frame

这里是# This class is unchanged from the other answer that I linked to, # but I'll reproduce its source code below for convenience. from autoScrollbar import AutoScrollbar from Tkinter import Button, Canvas, Frame, HORIZONTAL, Tk, VERTICAL # This is the class I made - something isn't right with it. class AutoScrollable(Frame): def __init__(self, top, *args, **kwargs): Frame.__init__(self, top, *args, **kwargs) hscrollbar = AutoScrollbar(self, orient = HORIZONTAL) hscrollbar.grid(row = 1, column = 0, sticky = 'ew') vscrollbar = AutoScrollbar(self, orient = VERTICAL) vscrollbar.grid(row = 0, column = 1, sticky = 'ns') canvas = Canvas(self, xscrollcommand = hscrollbar.set, yscrollcommand = vscrollbar.set) canvas.grid(row = 0, column = 0, sticky = 'nsew') hscrollbar.config(command = canvas.xview) vscrollbar.config(command = canvas.yview) # Make the canvas expandable self.grid_rowconfigure(0, weight = 1) self.grid_columnconfigure(0, weight = 1) # Create the canvas contents self.frame = Frame(canvas) self.frame.rowconfigure(1, weight = 1) self.frame.columnconfigure(1, weight = 1) canvas.create_window(0, 0, window = self.frame, anchor = 'nw') canvas.config(scrollregion = canvas.bbox('all')) # This is an example of using my new class I defined above. # It's how I know my class isn't working quite right. root = Tk() autoScrollable = AutoScrollable(root) autoScrollable.grid(row = 0, column = 0, sticky = 'news') root.rowconfigure(0, weight = 1) root.columnconfigure(0, weight = 1) for i in xrange(10): for j in xrange(10): button = Button(autoScrollable.frame, text = '%d, %d' % (i, j)) button.grid(row = i, column = j, sticky = 'news') autoScrollable.frame.update_idletasks() root.mainloop() 的来源,我将其包括在内,因为我在上面的来源中导入了它,但我不认为实际问题在这里。

autoScrollbar

1 个答案:

答案 0 :(得分:2)

当画布仍然为空时,您正在调用canvas.config(scrollregion = canvas.bbox('all')),从而有效地创建了滚动区(0, 0, 1, 1)

您应该等待定义scrollregion,直到Frame中有小部件。为此,您应该在AutoScrollable类中将canvas重命名为self.canvas并致电

autoScrollable.canvas.config(scrollregion = autoScrollable.canvas.bbox('all'))

之后

autoScrollable.frame.update_idletasks()

您还可以将<Configure>事件绑定到autoScrollable.frame,同时调用update_idletasks()并更新scrollregion。这样,您不必担心自己再调用它,因为每当Frame的大小发生变化时它们都会更新。

    self.frame.bind('<Configure>', self.frame_changed)

def frame_changed(self, event):
    self.frame.update_idletasks()
    self.canvas.config(scrollregion = self.canvas.bbox('all'))