我尝试在python tkinter上根据用户输入的深度绘制递归树,以下是我目前为止的代码:
from tkinter import * # Import tkinter
import math
#angleFactor = math.pi/5
#sizeFactor = 0.58
class Main:
def __init__(self):
window = Tk() # Create a window
window.title("Recursive Tree") # Set a title
self.width = 200
self.height = 200
self.canvas = Canvas(window,
width = self.width, height = self.height,bg="white")
self.canvas.pack()
# Add a label, an entry, and a button to frame1
frame1 = Frame(window) # Create and add a frame to window
frame1.pack()
Label(frame1,
text = "Enter the depth: ").pack(side = LEFT)
self.depth = StringVar()
entry = Entry(frame1, textvariable = self.depth,
justify = RIGHT).pack(side = LEFT)
Button(frame1, text = "Display Recursive Tree",
command = self.display).pack(side = LEFT)
self.angleFactor = math.pi/5
self.sizeFactor = 0.58
window.mainloop() # Create an event loop
def drawLine(self, x1,x2,y1,y2):
self.canvas.create_line(x1,y1,x2,y2, tags = "line")
def display(self):
self.canvas.delete("line")
return self.paintBranch(int(self.depth.get()),self.width/2, self.height /2 , self.height/3, math.pi/2)
def paintBranch(self,depth, x1, y1, length, angle):
if depth >= 0:
x2 = x1 +int( math.cos(angle) * length)
y2 = y1 + int(math.sin(angle) * length)
# Draw the line
self.drawLine(x1,y1,x2,y2)
# Draw the left branch
self.paintBranch(depth - 1, x2, y2, length * self.sizeFactor, angle + self.angleFactor )
# Draw the right branch
self.paintBranch(depth - 1, x2, y2, length * self.sizeFactor, angle - self.angleFactor )
Main()
当用户输入depth=0
时,代码正在工作,但在depth >=1
中递归时,代码无法绘制树,我需要代码帮助,谢谢
您的主要问题是将
drawLine
方法的参数弄乱了。你把它定义为但你称之为
^{pr2}$因此传递给它的
y1
参数用于x2
参数,x2
参数用于y1
参数。在您还需要更改初始的
y1
值,并在从y1
计算y2
时更改符号,因为当您沿着屏幕向下移动时,Tkinter中的Y坐标会增加。在这是您代码的修复版本。在
相关问题 更多 >
编程相关推荐