Tkinter编写一个程序显示递归树
时间: 2024-05-16 14:14:23 浏览: 68
好的,以下是一个使用Tkinter显示递归树的示例代码:
```python
import tkinter as tk
class RecursiveTree:
def __init__(self, canvas, x, y, length, angle, depth):
self.canvas = canvas
self.x = x
self.y = y
self.length = length
self.angle = angle
self.depth = depth
def draw(self):
if self.depth > 0:
# 计算下一个分支的坐标
x2 = self.x + self.length * tk.cos(tk.radians(self.angle))
y2 = self.y - self.length * tk.sin(tk.radians(self.angle))
# 绘制当前分支
self.canvas.create_line(self.x, self.y, x2, y2, width=self.depth, fill='brown')
# 递归绘制左右两个分支
RecursiveTree(self.canvas, x2, y2, self.length*0.7, self.angle+30, self.depth-1).draw()
RecursiveTree(self.canvas, x2, y2, self.length*0.7, self.angle-30, self.depth-1).draw()
if __name__ == '__main__':
root = tk.Tk()
root.geometry('500x500')
canvas = tk.Canvas(root, bg='white', width=500, height=500)
canvas.pack()
RecursiveTree(canvas, 250, 450, 80, -90, 8).draw()
root.mainloop()
```
这个示例代码中,我们使用了Tkinter的Canvas组件来绘制图形。我们定义了一个RecursiveTree类来表示递归树的每个节点,它包含当前节点的坐标、长度、角度和深度等信息。draw方法用来绘制当前节点,并递归绘制左右两个子节点。在主函数中,我们创建了一个Tkinter窗口,并将Canvas添加到窗口中,最后调用RecursiveTree类来绘制递归树。
阅读全文