I have written a script that takes in a file of the format
JavaScript
x
8
1
handgun: bullets magazines
2
bullets: labor ore
3
magazines:
4
ore:
5
labor:
6
bombs: ore
7
turret: bullets
8
Where each line in the list represents a ‘parent’ node and its list of ‘child’ nodes. So far I have written a script such that these nodes are printed out like a tree, and now I want to try to draw lines/arrows between these nodes. My current python script is as follows:
JavaScript
1
103
103
1
from ast import Delete
2
from dataclasses import replace
3
from os import link, remove
4
from tkinter import Canvas, Frame
5
import string
6
import tkinter as tk
7
import re
8
9
def fileReadIn():
10
f = open("list.txt", "r")
11
12
links = []
13
14
for line in f:
15
if re.search('.*:.*', line) != None:
16
parentAndChild = re.split(':', line)
17
childStr = parentAndChild[1]
18
childStr = childStr.replace('n', '')
19
newChilStr = childStr.split(' ')
20
newChilStr.remove('')
21
newChilStr.remove('')
22
parentAndChild[1] = newChilStr
23
links.append(parentAndChild)
24
25
f.close()
26
27
return links
28
29
30
#read in the masterlist from the file as a list, and links as dictionary, then and
31
generate the tree
32
links = fileReadIn()
33
34
#open the gui window
35
window = tk.Tk()
36
window.geometry('800x800')
37
38
cur_row = []
39
pos_x = 300
40
pos_y = 0
41
42
#generate the top row
43
for i in links:
44
isChild = False
45
46
#make a node for the parent
47
nodeparent = tk.Label(text=str(i[0]), background='black', name=str(i[0]))
48
#check to see if node is a child of any other node - if not, place at top of window
49
for m in links:
50
for k in m[1]:
51
if str(k) == str(i[0]):
52
isChild = True
53
54
if isChild == False:
55
nodeparent.place(x=pos_x, y=pos_y)
56
pos_x += 80
57
cur_row.append(str(i[0]))
58
59
#make the rest of the rows
60
treeFinished = False
61
pos_y += 80
62
pos_x = 300
63
children = []
64
temp_row = []
65
66
67
while treeFinished == False:
68
treeFinished = True
69
70
for i in cur_row:
71
for j in links:
72
if i == j[0]:
73
if len(j[1]) != 0:
74
treeFinished = False
75
76
for i in cur_row:
77
for j in links:
78
if i == j[0]:
79
children = j[1]
80
for k in children:
81
if k in temp_row:
82
continue
83
else:
84
node = tk.Label(text=k, background='black', name=k).place(x=pos_x, y=pos_y)
85
temp_row.append(k)
86
pos_x += 80
87
88
for i in temp_row:
89
for j in temp_row:
90
for k in links:
91
if j == k[0]:
92
for m in k[1]:
93
if i == m:
94
window.children[i].destroy()
95
temp_row.remove(i)
96
97
cur_row = temp_row
98
temp_row = []
99
pos_y += 80
100
pos_x = 300
101
102
window.mainloop()
103
I’ve tried using a canvas to do a create_line but was unsuccessful with this. Maybe I’m just missing something obvious, but does anyone have any advice on how to approach this?
Advertisement
Answer
Update: I fixed this issue! It turns out I just needed to scale the canvas to be the same size as my window.