我一直在努力理解二叉树的绘制。我在
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中的代码相对应。
请您参考如下方法:
很难确定,因为缺少依赖项我无法运行你的代码,但如果我不得不猜测,我会说这是因为你没有打包框架,这样它就会扩展和收缩.你说滚动条“落后了”,但我敢打赌 Canvas 也有同样的问题。
尝试修改打包框架的行:
frame.pack(side="top", fill="both", expand=True)
