我一直在努力了解二叉树的绘制。
我找到了一个出色的首发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中的代码。
答案 0 :(得分:1)
由于缺少依赖关系我无法运行您的代码,因此很难确定,但如果我不得不猜测,我会说这是因为您没有打包框架以便它会扩展和收缩。你说滚动条“落后”但我敢打赌画布也有同样的问题。
尝试修改包装框架的行:
frame.pack(side="top", fill="both", expand=True)