我一直在尝试理解二叉树的绘制。我在
http://billmill.org/pymag-trees/
提供的代码使用了不属于我认识的任何 python 库的图形调用,因此我已将图形调用转换为 tkinter 并让代码运行,除了一个意外行为。当我调整框架的大小(使其更大)时,滚动条会在某些时候被抛在后面。当它重新调整大小时,它们不会留在框架中。这是代码:
from tkinter import *
from gen import Tree
from demo_trees import trees
from knuth import layout
r = 30
rh = r*1.5
rw = r*1.5
def drawt(canvas, root, depth):
canvas.create_oval(root.x * rw, depth * rh,
root.x * rw + r, depth * rh + r,
fill = 'white',
width = 2)
for child in root.children:
drawt(canvas, child, depth+1)
def drawconn(canvas, root, depth):
for child in root.children:
canvas.create_line(root.x * rw + (r/2), depth * rh + (r/2),
child.x * rw + (r/2), (depth+1) * rh + (r/2),
width = 2)
drawconn(canvas, child, depth+1)
def main():
root = Tk()
# Create the main frame. The frame will include a
# scrollable canvas.
frame = Frame(root, width=500, height=309, relief=SUNKEN)
frame.grid_rowconfigure(0, weight=1)
frame.grid_columnconfigure(0, weight=1)
# Add scroll bars
xscrollbar = Scrollbar(frame, orient=HORIZONTAL)
xscrollbar.grid(row=1, column=0, sticky=E+W)
yscrollbar = Scrollbar(frame)
yscrollbar.grid(row=0, column=1, sticky=N+S)
# Add the canvas
canvas = Canvas(frame, width=500, height=300,
scrollregion=(-20, -20, 500, 300),
xscrollcommand=xscrollbar.set,
yscrollcommand=yscrollbar.set)
canvas.grid(row=0, column=0, sticky=N+S+E+W)
xscrollbar.config(command=canvas.xview)
yscrollbar.config(command=canvas.yview)
frame.pack()
# Now draw the tree
t = layout(trees[2])
drawconn(canvas, t, 0)
drawt(canvas, t, 0)
root.mainloop()
if __name__ == '__main__':
main()
绘图正常滚动,一切都很好,直到调整框架大小(更大) 谁能告诉我为什么滚动条不随框架移动?
如果有人感兴趣,完整的树绘制代码来自上面的链接,并且对应于提供的下载的figure2.py中的代码。