【发布时间】:2015-07-13 03:09:23
【问题描述】:
我想在the answer here 的基础上创建一个Tkinter class,这是一个Frame,它会根据需要在内容周围自动显示/隐藏Scrollbars。
我在上面链接的答案非常适合我的需要,但需要注意的是,因为它不包含在 class 中,所以它是不可重复使用的。我认为这将非常快速和简单,但由于某种原因,一旦我将代码重构为自己的class,我的AutoScrollbars 就永远不会出现,无论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 的源代码,我将其包括在内是因为我将它导入到上述源代码中,但我认为实际问题不在这里。
# Adapted from here: http://effbot.org/zone/tkinter-autoscrollbar.htm
from Tkinter import Scrollbar
class AutoScrollbar(Scrollbar):
'''
A scrollbar that hides itself if it's not needed.
Only works if you use the grid geometry manager.
'''
def set(self, lo, hi):
if float(lo) <= 0.0 and float(hi) >= 1.0:
self.grid_remove()
else:
self.grid()
Scrollbar.set(self, lo, hi)
def pack(self, *args, **kwargs):
raise TclError('Cannot use pack with this widget.')
def place(self, *args, **kwargs):
raise TclError('Cannot use pack with this widget.')
【问题讨论】:
标签: python tkinter scrollbar tkinter-canvas