Tkinter编写一个程序显示递归树且可控制分叉数
时间: 2024-05-13 13:19:35 浏览: 93
以下是一个简单的 Tkinter 程序,它可以显示递归树,并且可以通过输入框来控制分叉数:
```python
import tkinter as tk
import math
class RecursiveTreeApp(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.canvas = tk.Canvas(self, width=600, height=600)
self.canvas.pack()
self.branches_entry = tk.Entry(self)
self.branches_entry.pack()
self.draw_button = tk.Button(self, text="Draw Tree", command=self.draw_tree)
self.draw_button.pack()
def draw_tree(self):
self.canvas.delete("all")
branches = int(self.branches_entry.get())
self.draw_branch(300, 500, 100, -math.pi/2, branches)
def draw_branch(self, x, y, length, angle, branches):
if branches == 0:
return
end_x = x + length * math.cos(angle)
end_y = y + length * math.sin(angle)
self.canvas.create_line(x, y, end_x, end_y)
for i in range(-branches//2 + 1, branches//2 + 1):
new_angle = angle + i * math.pi/branches
self.draw_branch(end_x, end_y, length*0.7, new_angle, branches//2)
root = tk.Tk()
app = RecursiveTreeApp(master=root)
app.mainloop()
```
这个程序使用了 `tk.Canvas` 组件来显示递归树。`draw_tree` 方法根据输入框中的分叉数来绘制递归树。`draw_branch` 方法递归地绘制分支。
阅读全文